[英]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.