使用@Value注入属性以抽象类 [英] Injecting property using @Value to abstract class

查看:1544
本文介绍了使用@Value注入属性以抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类,我试图在其中使用@Value批注从属性文件中注入值

I have an abstract class in which I am trying to use the @Value annotation to inject value from a property file

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;
     }
}

由于未设置sharedVal,所以我收到NullPointerException.我尝试在抽象类上添加@Component构造型,并且还是一样.

I am getting NullPointerException since sharedVal is not set. I tried adding @Component stereotype on the abstract class and still the same thing.

我可以通过这种方式将值注入抽象类吗?如果没有,该怎么办?

Can I inject value into abstract class this way? If not how can accomplish this?

推荐答案

我认为您会发现设置了sharedVal ,但是您试图在构造函数中过早使用它.在Spring使用@Value注释注入值之前,必须调用构造函数(必须被调用).

I think you'll find the sharedVal is being set, but you're trying to use it too soon in the constructor. The constructor is being called (must be called) before Spring injects the value using the @Value annotation.

与其在构造函​​数中处理值,不如尝试使用@PostContruct方法,例如:

Instead of processing the value in the constructor, try a @PostContruct method instead, eg:

@PostConstruct
void init() {
    //perform common action using sharedVal
 }

(或替代地,实现Spring的InitializingBean接口).

(or alternatively, implement Spring's InitializingBean interface).

这篇关于使用@Value注入属性以抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆