首页 > 解决方案 > 在 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一片空白。有什么方法可以使用shapeServiceinsideShape的构造函数吗?

标签: javaspringspring-boot

解决方案


问题是 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();
    }
}

即使没有必要,我更喜欢构造函数参数注入而不是自动装配,就像你的情况一样。构造函数注入通常被认为是更好的形式。 这是一篇解释原因的文章


推荐阅读