java - 在 Spring bean 的构造函数中访问运行时参数和其他 bean
问题描述
我在 spring-boot 应用程序中有两个 bean:
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class Shape {
@Resource
private ShapeService shapeService;
private String name;
private String description;
public Shape(String name) {
this.name = name;
this.description = shapeService.getDescription();
}
}
@Service
public class ShapeService {
public String getDescription() {
return "This is a shape.";
}
}
我Shape
使用以下代码创建了实例:
Shape shape = beanFactory.getBean(Shape.class, "shape");
但我NullPointerException
在以下行得到了一个:
this.description = shapeService.getDescription();
shapeService
一片空白。有什么方法可以使用shapeService
insideShape
的构造函数吗?
解决方案
问题是 Spring 必须先创建一个对象,然后才能对其进行字段注入。因此,您引用的字段尚未由 Spring 设置,但稍后会在对象完全构造后设置。如果该行采用常规方法,它将起作用。
要解决此问题,您必须让 Spring 通过构造函数参数将对您的构造函数的引用传递给ShapeService
您的构造函数。将类的代码更改为Shape
如下所示:
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class Shape {
private ShapeService shapeService;
private String name;
private String description;
public Shape(String name, ShapeService shapeService) {
this.name = name;
this.shapeService = shapeService;
this.description = shapeService.getDescription();
}
}
即使没有必要,我更喜欢构造函数参数注入而不是自动装配,就像你的情况一样。构造函数注入通常被认为是更好的形式。 这是一篇解释原因的文章
推荐阅读
- python - 在一行 Python 中生成长度列表
- python - Pytorch RuntimeError: mat1 dim 1 必须匹配 mat2 dim 0
- amazon-web-services - 如何以编程方式将 EC2 实例加入域/Active Directory?
- html - 通过没有填充的“溢出:隐藏”防止截断盒子阴影
- matlab - MATLAB Simulink:代数循环错误“包含在时间 0.0 计算的 __ 的循环中的代数状态为 Inf 或 NaN”
- html - 调整 HTML 表格列的大小
- python - 将字典应用于正则表达式
- javascript - 有没有办法在 Howler.js 中查看音频下载的进度?
- google-bigquery - google big query 出现错误 查询指定了一个或多个联合数据源,但未扫描所有数据源
- php - 如何在 NetBeans 中运行单个文件而不是整个项目?