I have an interface and service implements it. It has some void methods. I am using spring java bean configuration. But unable to create bean object because of void
methods.How to handle this problem.
I tried to use @PostConstruct
instead of @Bean
after reading some blogs, but it didn't work out.
public interface MyInterface {
void someData(List<MyClass> list, String somedata);
}
@Service("myInterface")
public DummyClass implements MyInterface {
public void someData(List<MyClass> list, String somedata){
// my business logic
}
}
public AppConfig {
@Bean
public MyInterface myInterface {
return new DummyClass(); // but gives error void cannot return value
}
}
My Junit looks like this
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = {AppConfig.class},
loader = AnnotationConfigContextLoader.class
)
public class MyTest {
@Autowired
DummyClass dummyClass;
// If I don't use AppConfig and simply autowire then I get
"Error creating bean name, unsatisfied dependency
}
How do I achieve dependency injection here?
Use @Configuration annotation on AppConfig class, with this all the beans defined on this class will be loaded on spring context.
If you use @Service annotation on DummyClass, you do not need to declare @Bean annotation because you are already saying to spring to detect this class for dependency injection. On the other hand use @Bean annotation to specify the instantiation of the class. Normally I let the @Bean to complex classes for dependency injection or to override configurations.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.