1.重写 ContextLoaderListener 监听器。
package com.ucap.xzsp.util; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.WebApplicationContextUtils; public class SpringLoaderListener extends ContextLoaderListener{ @Override public void contextInitialized(ServletContextEvent event) { // TODO Auto-generated method stub super.contextInitialized(event); ServletContext context=event.getServletContext(); ApplicationContext ctx=WebApplicationContextUtils.getRequiredWebApplicationContext(context); SpringContextutil.setContext(ctx); } }
2。新建一个辅助类。
package com.ucap.xzsp.util; import org.springframework.beans.BeansException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; public class SpringContextutil { private static ApplicationContext context; public static ApplicationContext getContext() { return context; } public static void setContext(ApplicationContext context) { SpringContextutil.context = context; } public static Object getBean(String name)throws BeansException{ return context.getBean(name); } @SuppressWarnings("unchecked") public static Object getBean(String name, Class requiredType) throws BeansException { return context.getBean(name, requiredType); } public static boolean containsBean(String name) { return context.containsBean(name); } public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException { return context.isSingleton(name); } @SuppressWarnings("unchecked") public static Class getType(String name) throws NoSuchBeanDefinitionException { return context.getType(name); } public static String[] getAliases(String name) throws NoSuchBeanDefinitionException { return context.getAliases(name); } }
5.在WEB.XML里面改变监听为重写的那个类
<listener> <listener-class> com.ucap.SpringLoaderListener </listener-class> </listener>
4.获取service 对象。
XzspWebappQuestionService question=(XzspWebappQuestionService)SpringContextutil.getBean("xzspWebappQuestionService");