Spring 支持超类上的 @Value 吗?

问题描述 投票:0回答:1

我很难找到 Spring

@Value
注释是否适用于超类/继承的明确答案。

class Base {

    @Value("${app.some.property:hello}")
    private String someProperty;

    protected String getSomeProperty(){
        return someProperty;
    }
}

class MyClass extends Base {
    @Value("${app.other.property:world}")
    private String otherProperty;

    @PostConstruct
    void init(){
        System.out.println(getSomeProperty() + " " + otherProperty);
    }
}

这会产生

hello world
吗?

java spring
1个回答
0
投票

虽然这似乎没有记录,但它确实有效。

我调试了一下,发现 Spring Framework (V6.1.6) 源代码中检查所有超类中的可注入字段的地方 AutowiredAnnotationBeanPostProcessor#buildAutowiringMetadata

    private InjectionMetadata buildAutowiringMetadata(Class<?> clazz) {

        // [...]

        final List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
        Class<?> targetClass = clazz;

        do {
            // [...]
            targetClass = targetClass.getSuperclass();
        }
        while (targetClass != null && targetClass != Object.class);

        return InjectionMetadata.forElements(elements, clazz);
    }
© www.soinside.com 2019 - 2024. All rights reserved.