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

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

问题描述

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

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来进行二传手注入.我刚才用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天全站免登陆