I am having trouble finding a definitive answer whether Spring @Value
annotations work on super-class / are inherited.
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);
}
}
will this yield hello world
?
While this does not seem to be documented, it does work.
I debugged around and found the place in Spring Framework (V6.1.6) source code that checks all super-classes for injectable fields in
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);
}