问题描述
下列代码是在业务系统启动时执行,将信息保存到application。public class MyContextListener implements ServletContextListener {public void contextDestroyed(ServletContextEvent arg0) {// TODO Auto-generated method stub}public void contextInitialized(ServletContextEvent arg0) {ServletContext application = arg0.getServletContext();application.setAttribute("a", "aaa");application.setAttribute("b", "bbb");System.out.println(application.getAttribute("a"));System.out.println(application.getAttribute("b"));}}下列是如何实现,请帮忙看一下??????处该如何填写或者,怎么实现在任何类中提取当前系统中的application(注:在不能获取到request、response、session的情况下实现)public class Test { public void getApplication() { ServletContext application = ??????;}}问题补充谢谢各位:)
解决方案
将application存到一个静态类中去
解决方案二:
晕,不好意思,看错了,不过意思差不多
解决方案三:
自己写个类继承ContextLoaderListener,获取到ApplicationContext,然后注入给一个工具类的静态变量,后面通过工具类来获取ApplicationContext。具体代码:/** * ContextLoaderListener子类. * 把ApplicationContext赋给SpringContextUtil的静态变量Context. */public class ContextLoaderListener extends org.springframework.web.context.ContextLoaderListener { public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); super.contextInitialized(event); ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context); SpringContextUtil.setApplicationContext(ctx); }}** * 保存由ContentextLoadListener载入的ApplicationContext 静态变量 * 并实现了BeanFactory接口的委托,简化客户代码调用。 */public class SpringContextUtil { private static ApplicationContext context; public static void setApplicationContext(ApplicationContext acx) { context = acx; } public static ApplicationContext getApplicationContext() { return context; } public static Object getBean(String name) throws BeansException { return context.getBean(name); } 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); } public static Class getType(String name) throws NoSuchBeanDefinitionException { return context.getType(name); } public static String[] getAliases(String name) throws NoSuchBeanDefinitionException { return context.getAliases(name); }}在web.xml里面配置spring的监听器 <!--Spring Context loader--> <listener> <listener class>com.ffcs.common.spring.ContextLoaderListener</listener-class> </listener>
解决方案四:
你原来是这个意思。。。逆行其道,像HTTPSERVLET是网络传输协议,并不是类传输,我想问你,那个APPLICATION的值,凭什么能传过类这儿来?你可以如此改造一下类的构造public test(ServletContext application){.....}将application的值传递过来