怎么获取application
发布网友
发布时间:2022-11-13 13:38
我来回答
共1个回答
热心网友
时间:2024-11-19 00:16
自己写个类继承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>