2
votes

I am using Java-based Spring configuration in my project, specifying bean construction in @Bean-annotated methods in @Configuration. Recently, Recently, I've started to think that maybe it would've been better to use @Autowired to remove all non-important beans from @Configuration, leaving only small "root" set of them (key services and technical beans like those of Spring MVC).

Unfortunately, it seems that Spring can notice implementations for @Autowired dependencies only if they are inside component-scanned package which I cannot do without resorting to some XML.

Is there any way to use @Autowired with Java-based configuration without explicitly specifying each bean?

2
@Autowired works just fine inside normal @Bean-style configs, component-scanning is not required (or even desirable). Please give an example of what you have. - skaffman
For example, I have a @Bean MyService service that has an @Autowired IDao dao. There is an interface IDao and class DaoImpl implements IDao and there are no other implementations for IDao. As I understand, it is necessary to either declare a @Bean IDao dao() { return new DaoImpl } or use component scanning. Otherwise, I'm getting the No matching bean of type IDao found for dependency exception. - Fixpoint
You can component scan using @ComponentScan. No need for XML. - Nick

2 Answers

4
votes

If I understand you correctly, you're expecting Spring to auto-discover the DaoImpl class based on the autowired dependency on the Dao interface.

This isn't going to happen - you either need to use component scanning, or you need to explicitly declare the bean, either as <bean> or @Bean.

The reason for this is that Java provides no mechanism to discover classes which implement a given interface, the classloader just doesn't work that way.

0
votes

If you are implementing the Idao via dao and you are looking to @Autowire that dependency into your reference var... you need to first: define the bean so you (in Java Based Config) simply return the impl class to the interface. The bean name is that of your method name.

When you autowire this, it will search for a matching name between your reference variable you are looking to autowire and your declaration.

THEN you will be fine. Hope this helps.