在Spring项目中,经常有这样的需求,需要获取容器对象对,以便可以操作其它Bean实例或者对Bean进行分析处理。那是如何处理呢? Spring 提供两种方式,一种方式实现ApplicationContextAware接口,另种办法继承ApplicationObjectSupport。 下面我们看看代码是如何实现的。
接口实现方式 @Service public 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; } } 继承类实现方式 @Service public 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./schema/beans" xmlns:xsi="http://www./2001/XMLSchema-instance" xmlns:context="http://www./schema/context" xmlns:util="http://www./schema/util" xsi:schemaLocation="http://www./schema/beans http://www./schema/beans/spring-beans-3.2.xsd http://www./schema/context http://www./schema/context/spring-context-3.2.xsd http://www./schema/util http://www./schema/util/spring-util-3.2.xsd"> <!--组件扫描 --> <context:component-scan base-package="cn.opensv.example.spring.context" /> </beans> |
|