简体   繁体   English

没有自动装配注释的弹簧注入

[英]Spring inject without autowire annotation

I find some answer: https://stackoverflow.com/a/21218921/2754014 about Dependency Injection.我找到了一些答案: https : //stackoverflow.com/a/21218921/2754014关于依赖注入。 There isn't any annotation like @Autowired , @Inject or @Resource .没有像@Autowired@Inject@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" /> .让我们假设这个示例TwoInjectionStyles bean 没有任何 XML 配置(除了简单的<context:component-scan base-package="com.example" />

Is it correct to inject without specify annotation?在没有指定注释的情况下注入是否正确?

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.但是你仍然需要@Autowired来进行 setter 注入。 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.我刚才检查了Spring Boot 1.5.7 (使用Spring 4.3.11 ),当我删除@Autowired bean 没有被注入。

Yes, example is correct (starting from Spring 4.3 release).是的,示例是正确的(从 Spring 4.3 版本开始)。 According to the documentation ( this for ex), if a bean has single constructor, @Autowired annotation can be omitted.根据文档(例如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注入将@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. 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 可以在没有任何注入的情况下以常见方式使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM