Spring autowried in Abstract class construtor

autowired, constructor, java, spring

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);
}

Problem

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 ?

Original source