通过ApplicationContextAware加载Spring上下文环境(获取bean)

时间:2021-04-29 19:39:42

项目用到了ApplicationContextAware,通过它Spring容器会自动把上下文环境对象调用ApplicationContextAware接口中的setApplicationContext方法。

我们在ApplicationContextAware的实现类中,就可以通过这个上下文环境对象得到Spring容器中的Bean。

使用方法如下:

1.实现ApplicationContextAware接口:

package com.taotao.order.common;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringBeanUtil implements ApplicationContextAware {

private static ApplicationContext applicationContext;

@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringBeanUtil.applicationContext = applicationContext;
}

/**
* 通过名称在spring容器中获取对象
*
* @param beanName
* @return
*/

public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}

}

2.在Spring的配置文件中配置这个类,Spring容器会在加载完Spring容器后把上下文对象调用这个对象中的setApplicationContext方法:

<bean id="SpringBeanUtil " class="com.taotao.order.common.SpringBeanUtil" scope="singleton" />

3.在web项目中的web.xml中配置加载Spring容器的Listener:

<!-- 初始化Spring容器,让Spring容器随Web应用的启动而自动启动 -->  
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

4.在项目中即可通过这个SpringContextHelper调用getBean()方法得到Spring容器中的对象了。

package common;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import com.taotao.order.common.SpringBeanUtil;

@RunWith(SpringJUnit4ClassRunner.class) //表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations = {"classpath:spring/applicationContext-*.xml"})
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
@Transactional
public class SpringBeanUtilTest {
@Test
public void testGet() {
SpringBeanUtil.getBean("aa");
}
}