没有自动装配注释的弹簧注入 [英] Spring inject without autowire annotation

查看:31
本文介绍了没有自动装配注释的弹簧注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一些答案:https://stackoverflow.com/a/21218921/2754014 关于依赖注入.没有像 @Autowired@Inject@Resource 这样的注释.让我们假设这个例子没有任何 XML 配置 TwoInjectionStyles bean(除了简单的 <context:component-scan base-package="com.example"/>.

I find some answer: https://stackoverflow.com/a/21218921/2754014 about 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" />.

不指定注解注入是否正确?

Is it correct to inject without specify annotation?

推荐答案

从 Spring 4.3 开始,构造函数注入不需要注解.

From Spring 4.3 annotations are not required for constructor injection.

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 没有被注入.

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.

这篇关于没有自动装配注释的弹簧注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆