[英]Autowiring and annotation configuration in Spring
我有 2 個組件A
和B
。 A
取決於B
。 我寫了類似的東西:
public class A {
private B b;
@Autowired
public void setB(B b) {
this.b = b;
}
}
@Component
public class B {}
new XmlBeanFactory(new FileSystemResource("./spring.xml")).getBean(A.class);
配置
<context:annotation-config/>
<context:component-scan
base-package="com">
</context:component-scan>
<bean class="com.A" autowire="byType" />
它工作得很好。 現在我也想通過注釋配置A
。 所以我將@Component 注解添加到A
@Component
public class A {
private B b;
@Autowired
public void setB(B b) {
this.b = b;
}
}
並從配置中刪除A
描述。 所以它只是
<context:annotation-config/>
<context:component-scan
base-package="com">
</context:component-scan>
但是B不再注射了。 可能我應該指定自動裝配類型或類似的 smt。 那么我該如何解決呢?
您必須使用ApplicationContext
而不是普通的BeanFactory
。 似乎BeanFactory
不運行后處理器,包括尋找@Autowired
注釋的那個。 我將嘗試為此找到一份文檔,同時嘗試:
new ClassPathXmlApplicationContext("/spring.xml").getBean(B.class);
BTW @Autowired
在設置器、構造器、字段等上完全有效( 來源):
將構造函數、字段、設置方法或配置方法標記為由 Spring 的依賴注入工具自動裝配。
我覺得你應該試試
@Component
public class A {
@Autowired
private B b;
}
}
@Component
public class B {}
您可以參考以下鏈接中的示例: http://www.roseindia.net/tutorial/spring/spring3/ioc/autoscanig.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.