【问题标题】:Spring inject without autowire annotation没有自动装配注释的弹簧注入
【发布时间】:2018-03-13 09:27:43
【问题描述】:

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

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

【问题讨论】:

    标签: java spring dependency-injection annotations autowired


    【解决方案1】:

    从 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。

    【讨论】:

    【解决方案2】:

    是的,示例是正确的(从 Spring 4.3 版本开始)。根据文档(例如this),如果 bean 有 single 构造函数,则可以省略 @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 可以无需任何注射即可以普通方式使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多