Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting property using @Value to abstract class

Tags:

spring

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?

like image 204
ltfishie Avatar asked Jul 31 '13 03:07

ltfishie


People also ask

Can we inject in abstract class?

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.

What is @value annotation is used for?

Spring @Value annotation is used to assign default values to variables and method arguments.

Can we create Bean for abstract class?

You don't. You only declare the beans which have a concrete subclass of that abstract class.

What is the use of @value in spring boot?

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).


1 Answers

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).

like image 153
MattR Avatar answered Sep 21 '22 10:09

MattR