kub*_*a44 7 java spring annotations dependency-injection autowired
我找到了一些答案:https://stackoverflow.com/a/21218921/2754014关于依赖注入.没有任何注释@Autowired,@Inject或,或@Resource.让我们假设这个示例TwoInjectionStylesbean 没有任何XML配置(简单除外)<context:component-scan base-package="com.example" />.
在没有指定注释的情况下注入是否正确?
Krz*_*sik 10
从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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是你仍然需要@Autowired注射器.我刚用Spring Boot 1.5.7(使用Spring 4.3.11)检查过,当我删除时@Autowired,没有注入bean.
是的,示例是正确的(从Spring 4.3发布开始).根据文档(这个为ex),如果bean有单个构造函数,@Autowired则可以省略注释.
但有几个细微差别:
1.当存在单个构造函数并且使用@Autowired注释标记setter时,将逐个执行构造函数和setter注入:
@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
}
}
Run Code Online (Sandbox Code Playgroud)
2.另一方面,如果根本没有@Autowire(如在你的例子中),那么f对象将通过构造函数注入一次,并且setter可以在没有任何注入的情况下以常用方式使用.