[英]Spring inject without autowire annotation
我找到了一些答案: https : //stackoverflow.com/a/21218921/2754014關於依賴注入。 沒有像@Autowired
、 @Inject
或@Resource
這樣的注釋。 讓我們假設這個示例TwoInjectionStyles
bean 沒有任何 XML 配置(除了簡單的<context:component-scan base-package="com.example" />
。
在沒有指定注釋的情況下注入是否正確?
從 Spring 4.3 開始,構造函數注入不需要注解。
public class MovieRecommender {
private CustomerPreferenceDao customerPreferenceDao;
private MovieCatalog movieCatalog;
//@Autowired - no longer necessary
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}
@Autowired
public setMovieCatalog(MovieCatalog movieCatalog) {
this.movieCatalog = movieCatalog;
}
}
但是你仍然需要@Autowired
來進行 setter 注入。 我剛才檢查了Spring Boot 1.5.7
(使用Spring 4.3.11
),當我刪除@Autowired
bean 沒有被注入。
是的,示例是正確的(從 Spring 4.3 版本開始)。 根據文檔(例如this ),如果 bean 具有單個構造函數,則可以省略@Autowired
注釋。
但是有幾個細微差別:
1.當存在單個構造函數並且setter被@Autowired
注解標記時,構造函數和setter注入將@Autowired
執行:
@Component
public class TwoInjectionStyles {
private Foo foo;
public TwoInjectionStyles(Foo f) {
this.foo = f; //Called firstly
}
@Autowired
public void setFoo(Foo f) {
this.foo = f; //Called secondly
}
}
2.另一方面,如果根本沒有@Autowire
(如您的示例),那么f
對象將通過構造函數注入一次,並且 setter 可以在沒有任何注入的情況下以常見方式使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.