Question

I have a scenario where autowired is null when called in the constructor of an abstract class like this :

public abstract class AbstractClass{
   @Autowired 
   @Qualifier("proId")
   protected Prop prop;

     public AbstractClass(){ 
         prop.getName(); 

The above throws NullException on deployment.

But the following works when the autowired property called after instantiating

public abstract class AbstractClass{
   @Autowired 
   @Qualifier("proId")
   protected Prop prop;

     public void Init(){ 
         prop.getName(); 
       }
 }


public class DefaultClass extends AbstractClass(){ 
        ...

@autowired
DefaultClass dc ;
...

dc.Init(); 

How can I get the first case to work ?

Was it helpful?

Solution

You can't. Injection can only happen after an object has been created (or during construction with constructor injection). In other words, when prop.getName() is called inside the abstract class constructor, the field is still null since Spring hasn't processed it.

Consider refactoring your code so that your abstract class has a constructor that accepts a Prop argument and use constructor injection

public AbstractClass(Prop prop) {
    this.prop = prop;
    prop.getName();
} 
...
@Autowired
public DefaultClass(Prop prop) {
    super(prop);
}

OTHER TIPS

Do you know object creation life-cycle in Java? Spring doesn't do any magic about that.

There are multiple phases when using Spring for creating beans

  1. an object is instantiated using the constructor
  2. dependencies are injected into bean (obviously except for constructor dependencies which are passed through the object in first phase)
  3. objects @PostConstruct (or InitializingBean) methods are called.

Remember that before constructor there is no instance of your bean, so Spring can not wire anything in it!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top