java - Spring:没有@Component的@Autowired
问题描述
在一个真实的项目中,我发现@Component
以下代码中可能会省略:
// no @Component !!!!!
public class MovieRecommender {
private final CustomerPreference customerPreference;
@Autowired
public MovieRecommender(CustomerPreference customerPreference) {
this.customerPreference = customerPreference;
}
// ...
}
@Component
public class CustomerPreference {...}
(示例取自 Spring 官方文档https://docs.spring.io/spring-framework/docs/4.3.x/spring-framework-reference/htmlsingle/#beans-autowired-annotation,文档显示没有@Component
完全没有,这可能意味着它不是必需的,或者它只是没有显示。)
我工作的项目没有使用任何 XML bean 声明,但它使用了 Spring 以外的框架,因此有可能将类声明为 bean。或者它可能是我们使用的 Spring 版本的一个特性,如果没有记录该特性,它可能会在以后被删除。
问题:
使用的类必须用(嗯,是一个bean)@Autowired
进行注释吗?@Component
有没有这方面的官方文件?
UPD伙计们,@Configuration
项目中没有也没有XML配置,我知道这样的声明从一个类中生成一个bean,但问题不在于它们。我什至在上面的问题中写了“(好吧,成为一个豆子)”来涵盖这一点。@Autowired
在不是 bean 的类中工作吗?或者它可能声明了使用它作为 bean 的类?
解决方案
根据https://stackoverflow.com/a/3813725/755804,autowireBean()
可以从未声明为bean 的类中自动装配 bean。
@Autowired
private AutowireCapableBeanFactory beanFactory;
public void sayHello(){
System.out.println("Hello World");
Bar bar = new Bar();
beanFactory.autowireBean(bar);
bar.sayHello();
}
和
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
public class Bar {
@Autowired
private Foo foo;
public void sayHello(){
System.out.println("Bar: Hello World! foo="+foo);
}
}
另一方面,默认情况下,最新的 Spring 不假定使用的类@Autowire
是@Component
-s。
UPD
至于提到的真实项目,堆栈跟踪显示构造函数是从createBean()
. 也就是说,框架从框架配置中声明的类创建 bean。
推荐阅读
- c# - Cassandra.ServerErrorException:'java.lang.NoClassDefFoundError:org/joda/time/ReadablePartial'
- angular - 在 angular5 中使用 *ngFor 获取特定值
- ftps - Duplicity 不适用于 lftp+ftps 后端
- html - 如何根据标签文本的宽度使html标签和输入框宽度相同
- python - 如何将 yapf 应用于目录下的每个 python 文件?
- git - 从一个分支移植到另一个分支
- javascript - p1.movement is not a function
- android - 如何设计从firebase中提取的数据
- python - 抓取图像并仅保存选定的图像
- python-3.x - 如何在 python 3 中将 .png 文件附加到 .csv 文件中?