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;
}
}
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?
Second, setter injection is possible in an abstract class, but it's risky if we don't use the final keyword for the setter method. The application may not be stable if a subclass overrides the setter method.
Spring @Value annotation is used to assign default values to variables and method arguments.
You don't. You only declare the beans which have a concrete subclass of that abstract class.
One of the most important annotations in spring is @Value annotation which is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. It also supports Spring Expression Language (SpEL).
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.
Instead of processing the value in the constructor, try a @PostContruct
method instead, eg:
@PostConstruct
void init() {
//perform common action using sharedVal
}
(or alternatively, implement Spring's InitializingBean interface).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With