Spring中ApplicationContextAware的作用
本文内容纲要:
ApplicationContextAware
通过它Spring容器会自动把上下文环境对象调用ApplicationContextAware
接口中的setApplicationContext
方法。
我们在ApplicationContextAware
的实现类中,就可以通过这个上下文环境对象得到Spring容器中的Bean。
看到—Aware就知道是干什么的了,就是属性注入的,但是这个ApplicationContextAware的不同地方在于,实现了这个接口的bean,当spring容器初始化的时候,会自动的将ApplicationContext注入进来:
使用方法如下:
1.实现ApplicationContextAware接口:
importorg.springframework.beans.BeansException;
importorg.springframework.beans.factory.InitializingBean;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.ApplicationContextAware;
importcom.co.ayz.rpc.registry.ServiceRegistry;
publicclassRpcServerimplementsApplicationContextAware{
privateApplicationContextcontext;
@Override
publicvoidsetApplicationContext(ApplicationContextapplicationContext)
throwsBeansException{
//TODOAuto-generatedmethodstub
context=applicationContext;
}
//获得applicationContext
publicstaticApplicationContextgetApplicationContext(){
//assertContextInjected();
returncontext;
}
publicstaticvoidclearHolder(){
context=null;
}
//获取Bean
publicstatic<T>TgetBean(Class<T>requiredType){
//assertContextInjected();
return(T)getApplicationContext().getBean(requiredType);
}
@SuppressWarnings("unchecked")
publicstatic<T>TgetBean(Stringname){
assertContextInjected();
return(T)getApplicationContext().getBean(name);
}
//判断application是否为空
publicstaticvoidassertContextInjected(){
Validate.isTrue(context==null,"application未注入,请在springContext.xml中注入SpringHolder!");
}
}
因为我们在做开发的时候,并不是说在每一个地方都能将属性注入到我们想要的地方去的,比如在Utils使用到dao,我们就不能直接注入了,这个时候就是我们需要封装springContext的时候了,而ApplicationContextAware就起了关键性的作用。
自己写的demo:
/**
*@Title:SpringJobBeanFactory.java
*@Packagecom.founder.mrp.job
*@Description:TODO
*@versionV1.0
*/
packagecom.founder.mrp.job;
importorg.springframework.beans.BeansException;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.ApplicationContextAware;
importorg.springframework.stereotype.Component;
@Component
publicclassSpringJobBeanFactoryimplementsApplicationContextAware{
privatestaticApplicationContextapplicationContext;
@Override
publicvoidsetApplicationContext(ApplicationContextapplicationContext)throwsBeansException{
SpringJobBeanFactory.applicationContext=applicationContext;
}
publicstaticApplicationContextgetApplicationContext(){
returnapplicationContext;
}
@SuppressWarnings("unchecked")
publicstatic<T>TgetBean(Stringname)throwsBeansException{
if(applicationContext==null){
returnnull;
}
return(T)applicationContext.getBean(name);
}
}
使用:
TypeSetErpServicetypeSetErpServ=SpringJobBeanFactory.getBean("typeSetErpServiceImpl");
本文内容总结:
原文链接:https://www.cnblogs.com/loong-hon/p/10917755.html