user1809913
user1809913

Reputation: 1865

Is there any way to inject a dependency so that it can be used in the constructor?

I have object A

@Component("a")
Class A{
   public SomeObject getC(){
       return anObject;
   }
}

that I want to use in the construction of another object B like so

@Service("b")
Class B{
   @Autowired
   @Qualifier("a")
   A a;

   SomeObject c;

   public B(){

      c = a.getC();
   }

Where a is a connector to a database. Basically I want to load object c from the database upon initialization and still be able to get updates to the database afterwards. The problem is I tried doing this and I get the following initialization error.

 org.springframework.beans.factory.BeanCreationException: Error creating bean with name  defined in file
 Instantiation of bean failed;
 Could not instantiate bean class
 Constructor threw exception; nested exception is java.lang.NullPointerException

Is this even possible since the dependency must be injected before the object B has been constructed, or how would I do this?

Upvotes: 1

Views: 49

Answers (2)

There are two solutions to your problem. You can in fact use constructor injection with Spring, but you might instead want to use a method annotated @PostConstruct. It'll get executed after all of the necessary injections have happened but before the bean is put into service (e.g., by being made available to another bean or to a servlet), and you can execute any code you like there with the knowledge that the bean is in a valid constructed state.

@Service("b")
class B {
    @Autowired
    @Qualifier("a")
    A a;

    SomeObject c;

    public B(){}

    @PostConstruct
    private void initializeSomeObject() {
        c = a.getSomeObject();
    }
}

Upvotes: 2

morgano
morgano

Reputation: 17422

Beans are created first and then its dependencies are injected, that's why you're getting the NullPointerException. Try this:

@Service("b")
Class B{

    A a;

    SomeObject c;

    @Autowired
    @Qualifier("a")
    public B(A a){
        this.a = a;
        c = a.getC();
    }
}

Upvotes: 1

Related Questions