Spring中ApplicationContextAware的作用
通过ApplicationContextAware
,Spring容器会自动调用上下文环境对象ApplicationContextAware
接口中的setApplicationContext
方法,从而获得容器中的指定Bean。
自定义一个ApplicationContextAware
的实现类,就可以通过这个上下文环境对象得到Spring容器中的Bean。
看到Aware就知道是干什么的了,这个ApplicationContextAware的不同地方在于,实现了这个接口的类,当spring容器初始化的时候,会自动的将ApplicationContext注入进来:
使用方法如下:
1.实现ApplicationContextAware接口:
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class RpcServer implements ApplicationContextAware{
private ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
// TODO Auto-generated method stub
this.context = applicationContext;
}
//获得applicationContext
public static ApplicationContext getApplicationContext() {
//assertContextInjected();
return context;
}
public static void clearHolder(){
context=null;
}
//获取Bean
public static <T> T getBean(Class<T> requiredType){
//assertContextInjected();
return (T) getApplicationContext().getBean(requiredType);
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name){
assertContextInjected();
return (T) getApplicationContext().getBean(name);
}
//判断application是否为空
public static void assertContextInjected(){
Validate.isTrue(context==null, "application未注入 ,请在springContext.xml中注入SpringHolder!");
}
}
实际开发的时候,并不是说在每一个地方都能将属性注入到我们想要的地方去的,比如在Utils使用到dao,我们就不能直接注入了,这个时候就是我们需要封装springContext的时候了,而ApplicationContextAware就起了关键性的作用。
使用案例
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringJobBeanFactory implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringJobBeanFactory.applicationContext=applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
if (applicationContext == null){
return null;
}
return (T)applicationContext.getBean(name);
}
}
使用:
TypeSetErpService typeSetErpServ = SpringJobBeanFactory.getBean("typeSetErpServiceImpl");
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix