微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Spring bean的构造函数中访问运行时参数和其他bean

如何解决在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的构造函数中使用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解释了原因

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。