打开APP
userphoto
未登录

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

开通VIP
Spring Bean中如何获取ApplicationContext

在Spring项目中,经常有这样的需求,需要获取容器对象对,以便可以操作其它Bean实例或者对Bean进行分析处理。那是如何处理呢?

Spring 提供两种方式,一种方式实现ApplicationContextAware接口,另种办法继承ApplicationObjectSupport。

下面我们看看代码是如何实现的。

 

接口实现方式

@Servicepublic class SpringContextHelper implements ApplicationContextAware {    private ApplicationContext context;            //提供一个接口,获取容器中的Bean实例,根据名称获取    public Object getBean(String beanName)    {        return context.getBean(beanName);    }        @Override    public void setApplicationContext(ApplicationContext context)            throws BeansException {        this.context = context;            }}
 
继承类实现方式
 
@Servicepublic class SpringContextHelper2 extends ApplicationObjectSupport {            //提供一个接口,获取容器中的Bean实例,根据名称获取    public Object getBean(String beanName)    {        return getApplicationContext().getBean(beanName);    }    }

继承类的方式,是调用父类的getApplicationContext()方法,获取Spring容器对象。

 

我们再看看如何使用SpringContextHelper类。

public class ContectAwareTest {    private SpringContextHelper helper;    private SpringContextHelper2 helper2;    ApplicationContext context;    @Before    public void init() {        context = new ClassPathXmlApplicationContext("spring/spring.xml");        helper = (SpringContextHelper) context.getBean("springContextHelper");        helper2 = (SpringContextHelper2) context                .getBean("springContextHelper2");    }    @Test    public void testGetBean() {        // 能过SpringContextHelper 获取容器中的Bean        ExampleBean bean = (ExampleBean) helper.getBean("exampleBean");        bean.test();    }    @Test    public void testGetBean2() {        // 能过SpringContextHelper 获取容器中的Bean        ExampleBean bean = (ExampleBean) helper.getBean("exampleBean");        bean.test2();    }}

OK ,就这么简单。

 

附件,spring配置文件:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"    xmlns:util="http://www.springframework.org/schema/util"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">    <!--组件扫描 -->    <context:component-scan base-package="cn.opensv.example.spring.context" /></beans>

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
普通Java类获取Spring的bean
Dubbo学习之简单环境搭建
SSM框架(一)
SSH框架搭建
Spring,Bean对象实例化
你究竟有多了解Spring?
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服