繁体   English   中英

构造函数中的Spring不需要的属性?

[英]Spring nonrequired properties in constructor?

我想通过构造函数注入将bean列表注入spring bean。

@Component
public void MyBean {
    @Autowired
    public MyBean(List<BeanToInject> beanList) {
        ...
    }
}

但是BeanToInject的实现在其他模块中。 这些模块可能已关闭。 如果applicationcontext中没有BeanToInject的实现,则spring会在启动时抛出异常而不是注入空列表。 我能做什么? (基于Setter和私有财产的自动装配对我来说不是一个选择。)

如果使用Java 8,则可以使用Optional:

@Autowired
public TestComponent(Optional<List<BeanToInject>> beanList) {
    if (beanList.isPresent()) {
        // There are beans in the list
    } else {
        // No beans injected
    }
}

在Spring中,Autowired可以具有所需的值来定义它在autowire时是否需要。 但这不适用于构造函数。 在您的情况下,最佳解决方案是在方法或属性中使用自动装配并应用
@Autowired(required=false) private List<BeanToInject> beanList;
要么
@Autowired(required=false) public void setBeanList(List<BeanToInject> beanList);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM