java 没有自动装配注释的弹簧注入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46523305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring inject without autowire annotation
提问by kuba44
I find some answer: https://stackoverflow.com/a/21218921/2754014about Dependency Injection. There isn't any annotation like @Autowired
, @Inject
or @Resource
. let's assume that there isn't any XML configuration for this example TwoInjectionStyles
bean (except simple <context:component-scan base-package="com.example" />
.
我找到了一些答案:https: //stackoverflow.com/a/21218921/2754014关于依赖注入。没有任何注释,如@Autowired
,@Inject
或@Resource
。让我们假设这个示例TwoInjectionStyles
bean没有任何 XML 配置(除了 simple <context:component-scan base-package="com.example" />
.
Is it correct to inject without specify annotation?
在没有指定注释的情况下注入是否正确?
回答by Krzysztof At?asik
From Spring 4.3 annotations are not required for constructor injection.
从 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;
}
}
But you still need @Autowired
for setter injection. I checked a moment ago with Spring Boot 1.5.7
(using Spring 4.3.11
) and when I removed @Autowired
then bean was not injected.
但是你仍然需要@Autowired
setter 注入。我刚才用Spring Boot 1.5.7
(using Spring 4.3.11
)进行了检查,当我删除时@Autowired
,没有注入 bean。
回答by Alex Saunin
Yes, example is correct (starting from Spring 4.3 release). According to the documentation (thisfor ex), if a bean has singleconstructor, @Autowired
annotation can be omitted.
是的,示例是正确的(从 Spring 4.3 版本开始)。根据文档(例如this),如果 bean 具有单个构造函数,@Autowired
则可以省略注释。
But there are several nuances:
但是有几个细微差别:
1.When single constructor is present and setter is marked with @Autowired
annotation, than both constructor & setter injection will be performed one after another:
1.当单个构造函数存在并且setter被@Autowired
注解标记时,构造函数和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
}
}
2.At the other hand, if there is no @Autowire
at all (as in your example), than f
object will be injected once via constructor, and setter can be used in it's common way without any injections.
2.另一方面,如果根本没有@Autowire
(如您的示例),则f
对象将通过构造函数注入一次,并且 setter 可以在没有任何注入的情况下以常见方式使用。