Spring 不使用自动装配注解注入

Spring inject without autowire annotation

我找到了一些答案: 关于依赖注入。没有像 @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 for ex),如果一个 bean 具有 单个 构造函数,则可以省略 @Autowired 注释。

但有几个细微差别:

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. 另一方面,如果根本没有 @Autowire(如您的 example),那么 f对象将通过构造函数注入一次,并且 setter 可以在没有任何注入的情况下以其常用方式使用。