Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 不带autowire注释的Spring注入_Java_Spring_Dependency Injection_Annotations_Autowired - Fatal编程技术网

Java 不带autowire注释的Spring注入

Java 不带autowire注释的Spring注入,java,spring,dependency-injection,annotations,autowired,Java,Spring,Dependency Injection,Annotations,Autowired,我找到了一些答案:关于依赖注入。没有任何类似于@Autowired、@Inject或@Resource的注释。让我们假设本例中没有任何XML配置TwoInjectionStylesbean(除了simple) 在不指定注释的情况下进行注入是否正确?来自Spring 4.3的注释对于构造函数注入是不需要的 public class MovieRecommender { private CustomerPreferenceDao customerPreferenceDao; pr

我找到了一些答案:关于依赖注入。没有任何类似于
@Autowired
@Inject
@Resource
的注释。让我们假设本例中没有任何XML配置
TwoInjectionStyles
bean(除了simple


在不指定注释的情况下进行注入是否正确?

来自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版本开始)。根据文档(例如),如果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
(如您的,而不是
f
对象将通过构造函数注入一次,并且setter可以用它的普通方式使用,而不需要任何注入。

所以这个anwser是不正确的?除非我遗漏了什么,否则它不会工作。所以你是对的,没有任何xml配置,这个答案是不正确的。这个官方示例有点误导我。我认为setter inj如果@Autowired没有参数构造函数,则section可以在没有@Autowired的情况下工作。