三、让Bean获取Spring容器
来源:互联网 发布:java字符串拼接函数 编辑:程序博客网 时间:2024/06/16 08:35
之前编写的程序中都是先获取Spring容器,再由容器的getBean(“id”,Object.class)方法来获取Spring容器中的bean实例。
但是在某些特殊情况下,bean中需要访问Spring容器本身,其实bean中一样也可以获取Spring容器。
以下是bean获取Spring容器的步骤。
1、首先编写一个实现了ApplicationAware接口的PersonBean类,实现了ApplicationAware接口的类即拥有访问Spring容器的能力。实现了ApplicationAware接口的类被容器创建创建以后,它会拥有一个引用,指向创建 它的BeanFactory.
package org.meify.bean;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;/** * 实现ApplicationContextAware 接口,从而使得bean获取Spring容器 * @description * @version 1.0 * @author meify 2014-1-2 下午3:30:32 */public class PersonBean implements ApplicationContextAware {private ApplicationContext ctx;@Overridepublic void setApplicationContext(ApplicationContext ctx) throws BeansException {// TODO Auto-generated method stubthis.ctx=ctx;}public ApplicationContext getCtx() {return ctx;}}
2、接下来就得在Spring-condig.xml配置文件中配置该bean了。
只需在xml文件中添加一行代码即可。
<bean id="person" class="org.meify.bean.PersonBean"></bean>
3、最后即可以在测试程序中测试一下了
package org.meify.test;import org.meify.bean.AuthorBean;import org.meify.bean.BookBean;import org.meify.bean.EmailEvent;import org.meify.bean.PersonBean;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * 获取Spring容器并获取bean实例 * 以下代码: * 先获取spring容器,再获取实体bean,将Spring接口与代码耦合在一起,造成代码污染。 * @description * @version 1.0 * @author meify 2014-1-2 下午2:33:48 */public class Test01 {public static void main(String[] args) {//ApplicationContext的实例即Spring容器,也称之为Spring上下文ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-config.xml");System.out.println(ctx);//3、测试bean获取Spring容器PersonBean person=ctx.getBean("person",PersonBean.class);ApplicationContext ctx1=person.getCtx();System.out.println("person实例获取的Spring 容器==="+ctx1);}}
控制台输出如下:
person实例获取的Spring 容器===org.springframework.context.support.ClassPathXmlApplicationContext@535b58: startup date [Fri Jan 03 09:51:51 CST 2014]; root of context hierarchy
表明Spring 容器生成的PerosnBean实例后,该实例能够获取到Spring容器。
0 0
- 三、让Bean获取Spring容器
- 让bean获取spring容器
- 让Bean获取Spring容器
- 让Bean获取Spring容器
- 7.4.5:让Bean获取Spring容器
- Bean获取Spring容器
- Bean获取Spring容器
- ApplicationContext的事件机制&&让Bean获取Spring容器
- 【Spring】Spring容器获取Bean
- Spring(三)——核心容器Bean
- java类获取spring容器的bean
- Java类获取spring 容器的bean
- 获取Spring 容器中bean的方法
- 通过ApplicationContextAware获取spring容器中的bean
- 获取spring容器中bean的方法
- 使用监听获取spring容器的bean
- 通过ApplicationContextAware获取spring容器中的bean
- Java类获取spring 容器的bean
- 安装mysql常出现的问题
- 处理问题要不着急、不邀功、延迟处理则能给你带来更高效以及更多的威信
- 注意静态代码块的使用
- perl 运维小技巧
- java 递归实现通配符匹配
- 三、让Bean获取Spring容器
- 关于nand flash上实现jffs2文件系统的学习
- 中文命名实体识别
- Nginx动态加载新的配置文件
- cocos2d-x中各种诡异BUG的一个原因
- [shell] sleep
- 指针数组、数组指针、指针函数、函数指针
- mahout基于hadoop的推荐引擎代码分析
- 牛蔚-移动互联网下的自媒体