问题描述
我在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
的构造函数中使用Shape
?
解决方法
问题在于,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();
}
}
即使您不需要自动构造,我也喜欢构造器参数注入而不是自动装配。通常认为构造函数注入是更好的形式。 Here's an article解释了原因