I have two spring beans as follows:
@Component("A")
@Scope("prototype")
public class A extends TimerTask {
@Autowired
private CampaignDao campaignDao;
@Autowired
private CampaignManager campManger;
A(){
init_A();
}
}
I have to make a new object of A with new keyword, due to a legacy code
@Component("B")
@Scope("prototype")
public class B{
public void test(){
A a = new A();
}
}
when Running -> the spring beans in the class A are null, can i create a new instance of the spring bean A and still use autowiring in it ?
Yours component “A” is not created by Spring container, thus, dependencies are not injected. However, if you need to support some legacy code (as I understand from your question), you can use
@Configurableannotation and build/compile time weaving:Then, Spring will inject autowired dependencies to component A, no matter if it’s instantiated by container itself, or if it’s instantiated in some legacy code by
new.For example, to set up build-time weaving with maven plugin you have to:
<context:spring-configured/>to the Spring application contextin the build plugins section:
…and the dependencies section:
Please consult Spring reference for more details:
http://static.springsource.org/spring/docs/current/spring-framework-reference/html/aop.html#aop-atconfigurable