一、前言
这边分别通过ServletContextListener容器启动时初始化获取Spring ApplicationContext上下文、主动注入指定Spring的xml配置文件获取其Spring ClassPathXmlApplicationContext上下文两个不同方式,获取各自Spring上下文的bean对象getBean方法,详情参见代码示例说明。
二、代码示例
1.ServletContextListener监听方式
<listener>@b@ <listener-class>com.xwood.pms.util.SpringContext</listener-class>@b@</listener>
package com.xwood.pms.util.SpringContext;@b@@b@import javax.servlet.ServletContextEvent;@b@import javax.servlet.ServletContextListener;@b@@b@import org.springframework.context.ApplicationContext;@b@import org.springframework.web.context.support.WebApplicationContextUtils;@b@@b@public class SpringContext implements ServletContextListener {@b@ @b@ private static ApplicationContext beanContext = null;@b@@b@ public static Object getBean(String beanId) {@b@ return beanContext.getBean(beanId);@b@ }@b@@b@ @Override@b@ public void contextDestroyed(ServletContextEvent arg0) {@b@ beanContext=null;@b@ }@b@@b@ @Override@b@ public void contextInitialized(ServletContextEvent event) {@b@ beanContext = WebApplicationContextUtils.getWebApplicationContext(event@b@ .getServletContext());@b@ @b@ }@b@}
2.ClassPathXmlApplicationContext方式
import org.springframework.beans.BeansException;@b@import org.springframework.beans.factory.config.BeanFactoryPostProcessor;@b@import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;@b@import org.springframework.context.support.ClassPathXmlApplicationContext;@b@@b@ @b@public class SpringBean {@b@@b@ public static ClassPathXmlApplicationContext context;@b@ private static String _paramString;@b@ private static Object _paramObject;@b@ @b@ static{@b@ context = new ClassPathXmlApplicationContext("classpath:test/applicationContext.xml");@b@ }@b@ @b@ public static void registerSingleton(String paramString, Object paramObject){@b@ _paramString=paramString;@b@ _paramObject=paramObject;@b@ context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor(){@b@ @Override@b@ public void postProcessBeanFactory(@b@ ConfigurableListableBeanFactory beanFactory)@b@ throws BeansException {@b@ beanFactory.registerSingleton(_paramString,_paramObject);@b@ };@b@ @b@ });@b@ }@b@ @b@ public static Object getBean(String id){@b@ return (Object)context.getBean(id);@b@ }@b@ @b@}
3. FileSystemXmlApplicationContext方式
import org.springframework.context.ApplicationContext;@b@import org.springframework.context.support.FileSystemXmlApplicationContext;@b@ @b@public class SpringBean {@b@@b@ public static ApplicationContext context;@b@ @b@ static{@b@ String path = SpringBean.class.getClassLoader().getResource("").getPath();@b@ context= new FileSystemXmlApplicationContext(path+"/applicationContext.xml"); @b@ }@b@ @b@ public static Object getBean(String id){@b@ return (Object)context.getBean(id);@b@ }@b@ @b@}