使用@Value注入属性以抽象类

ltf*_*hie 8 spring

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

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;
     }
}
Run Code Online (Sandbox Code Playgroud)

我收到NullPointerException,因为没有设置sharedVal.我尝试在抽象类上添加@Component构造型,但仍然是相同的.

我可以通过这种方式将值注入抽象类吗?如果没有,怎么能做到这一点?

Mat*_*ttR 18

我想你会发现sharedVal 设定,但是你要在构造函数中太早使用它.在Spring使用@Value注释注入值之前,正在调用构造函数(必须调用).

而不是在构造函数中处理值,而是尝试一种@PostContruct方法,例如:

@PostConstruct
void init() {
    //perform common action using sharedVal
 }
Run Code Online (Sandbox Code Playgroud)

(或者,实现Spring的InitializingBean接口).

  • 你应该触及任何注入值的最早的是后构造方法; 生命周期早期的属性状态是未定义的(嗯,通常为"null"或零为迂腐). (3认同)

Ken*_*han 5

我可以通过这种方式将值注入抽象类吗?

抽象类无法实例化,因此不能将任何内容注入抽象类。相反,您应该将值注入到其具体的子类中。

确保您的具体子类被@ComponentSpring 标记为构造型并且被“组件扫描”。@Component不需要抽象类上的,因为它无法实例化。


更新:我终于发现您正在尝试访问构造函数中的注入值,但发现该值未设置。这是因为Spring将在实例化bean之后注入值。因此,如果不使用构造函数注入,则无法在构造函数内部访问注入的值。您可以按照Matt的建议使用@PostContruct或实施InitializingBean

下面显示了是否使用XML配置:

<context:property-placeholder location="classpath:xxxxx.properties" ignore-unresolvable="true" />


<bean id="parent" class="pkg.Parent" abstract="true" init-method="postConstruct">
    <property name="sharedVal" value="${shared.val}" />
</bean>


<bean id="child" class="pkg.ChildA" parent="parent">
Run Code Online (Sandbox Code Playgroud)

使用sharedVal内部执行常见操作Parent#postConstruct()