自定义监听器 创建Bean

	<listener>
		<listener-class>com.listener.TestApplicationContextLoaderListener</listener-class>
	</listener>	
public class TestApplicationContextLoaderListener implements ServletContextListener{

	@Override
	public void contextDestroyed(ServletContextEvent servletcontextevent) {
		System.out.println("调用:TestApplicationContextLoaderListener11");
		TestApplicationContext.initTspApplicationContext(WebApplicationContextUtils.getRequiredWebApplicationContext(servletcontextevent.getServletContext()));
	}

	@Override
	public void contextInitialized(ServletContextEvent servletcontextevent) {
		System.out.println("调用:TestApplicationContextLoaderListener22");
		//TestApplicationContext.initTspApplicationContext(WebApplicationContextUtils.getRequiredWebApplicationContext(servletcontextevent.getServletContext()));
		
		//或这样也可以
		ApplicationContext factory = new ClassPathXmlApplicationContext("classpath*:applicationContext-*.xml");
		TestApplicationContext.initTspApplicationContext(factory);
	}

}
import org.springframework.context.ApplicationContext;

public class TestApplicationContext {
	private static ApplicationContext _applicationContext;

	public static void initTspApplicationContext(
			ApplicationContext applicationContext) {
		_applicationContext = applicationContext;
	}

	public static Object getBean(String beanid) {
		Object bean = null;
		if (null == _applicationContext) {
			throw new RuntimeException("应用上下文未正常初始化。");
		}
		try {
			bean = _applicationContext.getBean(beanid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bean;
	}
}
	@RequestMapping(value = "/getBean.do", method = RequestMethod.GET )
    public void getBean(HttpServletRequest request){
		//获取类的名字
		String objName = this.getClass().getName();
		//返回bean对象引用
		TestBean cacheManager = (TestBean)TestApplicationContext.getBean("testBean");
		cacheManager.refBean();
    }
	<bean id="testBean" class="com.service.TestBean">
	</bean>

猜你喜欢

转载自xinjiatao.iteye.com/blog/2213488