我有一个抽象类,我试图在其中使用 @Value 注释从属性文件中注入(inject)值
public abstract class Parent {
@Value ("${shared.val}")
private String sharedVal;
public Parent() {
//perform common action using sharedVal
}
}
@Component
public class ChildA extends Parent {
Param a1;
@Autowired
public ChildA (Param a1) {
super();
this.a1 = a1;
}
}
我收到 NullPointerException 因为 sharedVal 未设置。我尝试在抽象类上添加 @Component 原型(prototype),但仍然是一样的。
我可以通过这种方式将值(value)注入(inject)抽象类吗?如果没有怎么能做到这一点?
最佳答案
我想你会发现 sharedVal 正在被设置,但你试图在构造函数中过早地使用它。在 Spring 使用 @Value
注入(inject)值之前调用构造函数(必须调用)注解。
不要在构造函数中处理值,而是尝试 @PostContruct
代替方法,例如:
@PostConstruct
void init() {
//perform common action using sharedVal
}
(或者,实现 Spring 的 InitializingBean 接口(interface))。
关于spring - 使用@Value 将属性注入(inject)抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17961257/