如何在基于 Java 的配置中使用 @Autowired?
我在我的项目中使用基于Java的Spring配置,在@Configuration中的@Bean注释方法中指定bean构造。最近,最近,我开始认为也许使用@Autowired从@Configuration中删除所有不重要的bean会更好,只留下其中的一小部分“根”集(关键服务和技术bean,例如那些Spring MVC)。
不幸的是,似乎 Spring 只能注意到 @Autowired 依赖项的实现,只有当它们位于组件扫描包内时,我才能在不诉诸某些 XML 的情况下做到这一点。
有没有办法在基于 Java 的配置中使用 @Autowired 而无需显式指定每个 bean?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我理解正确的话,您期望 Spring 根据对
Dao
接口的自动装配依赖项自动发现DaoImpl
类。这种情况不会发生——您要么需要使用组件扫描,要么需要显式声明 bean,无论是
还是@Bean
。原因是 Java 没有提供机制来发现实现给定接口的类,类加载器就不能那样工作。
If I understand you correctly, you're expecting Spring to auto-discover the
DaoImpl
class based on the autowired dependency on theDao
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.
如果您通过 dao 实现 Idao 并且您希望 @Autowire 将该依赖项添加到您的引用变量中...您需要首先:
定义 bean,以便您(在基于 Java 的配置中)只需将 impl 类返回到接口即可。 bean 名称是您的方法名称。
当您自动装配时,它将在您要自动装配的引用变量和声明之间搜索匹配的名称。
那么你就会没事的。希望这有帮助。
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.