Thursday, October 13, 2011

How to Autowire an argument to a constructor in Spring.

Look into this class:

public class SomeServiceImpl{


    @Autowired
    private AnotherService anotherService;


    public SomeServiceImpl(){
            doThisWithAnotherService();
    }


    private void doThisWithAnotherService(){
            anotherService.doThat();
    }
}


The above code will blowup while initilization with a NullPointerException inside the doThisWithAnotherService().  The reason being the constructor is called before AnotherService bean is injected.

Solution


public class SomeServiceImpl{


    private AnotherService anotherService;


    @Autowired
    public SomeServiceImpl(AnotherService aService){
        this.anotherService = aService;
        doThisWithAnotherService();
    }


    private void doThisWithAnotherService(){
        anotherService.doThat();
    }
}



Fields are injected right after construction of a bean before any config methods are invoked.

Source: http://static.springsource.org/spring/docs/2.5.x


No comments: