打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Spring中ApplicationContextAware接口使用理解

一、接口介绍
当一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得ApplicationContext中的所有bean。换句话说,就是这个类可以直接获取spring配置文件中,所有引用到的bean对象。

二、接口使用

1.编写工具类

 1 import org.springframework.beans.BeansException; 2 import org.springframework.context.ApplicationContext; 3 import org.springframework.context.ApplicationContextAware; 4 /** 5  * Created by zl on 2018/7/7. 6  */ 7 public class BeanFactoryUtil implements ApplicationContextAware { 8     protected static ApplicationContext ctx = null; 9  10     @Override11     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {12         ctx = applicationContext;13     }14  15     public static Object getBean(String beanId) {16         return ctx.getBean(beanId);17     }18 }

2.在applicationContext.xml中注册BeanFactoryUtil工具类

<bean id="beanFactoryUtil" class="com.boss.utils.BeanFactoryUtil"/>

3.测试

@Testpublic void test() {  new ClassPathXmlApplicationContext("applicationContext.xml");// 加载applicationContext.xml(模拟启动web服务)  UserDao userDaoImpl = (UserDao) BeanFactoryUtil.getBean("userDaoImpl");  userDaoImpl.sayHello();}

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
普通Java类获取Spring的bean
SpringContextUtil ApplicationContextAware static块中 null
spring 依赖注入到直接new 对象
Spring的@PostConstruct与ApplicationContextAware冲突问题
Spring知识点
springboot应用获取spring上下文的4种方式
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服