Suppose you have some java classes which are unable (or you don’t want it) to be wired to the Spring application context; for example, an auto generated web service client class! But you do want to use the dependency injection feature of Spring to get some of the other beans injected in to this class. How can we make this happen? One way to achieve this would be to use the ApplicationContextAware interface provided by Spring.
As we know, beans are loaded from ApplicationContext instance. So by implementing the callback interface, any bean can access the context and communicate with other beans directly. Create a class named ApplicationContext which implements ApplicationContextAware. The inherited method, ‘setApplicationContext(…)’ will get called during the creation of this bean, providing the reference to the context. Our program should store this for a later interaction with the context.
Example:
public interface CustomerService {
public void payBill(double amt);
}
public class CustomerServiceImpl implements CustomerService, ApplicationContextAware {
private ApplicationContext ctx;
@Override
public void setApplicationContext(ApplicationContext ctx) {
this.ctx = ctx;
}
private BillPaymentService createBillPaymentInstance() {
return ctx.getBean("billPaymentService", BillPaymentService.class);
}
public void payBill(double amt) {
//now get the bean and do whatever you want for that context
BillPaymentService billingService = createBillPaymentInstance();
//we need to call some method of BillPaymentService here. Right now not required.
}
}
No comments:
Post a Comment