获取Spring容器的方法
来源:互联网 发布:lol小兵数据 编辑:程序博客网 时间:2024/05/17 08:01
方法一:主要就是通过servletContext获取Spring容器
第一步:在web.xml定义request的上下文
第二步:通过request上下文得到servletContext,从而得到applicationContext
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
将上面代码封装成工具类public class ApplicationContextUtils {
private static ApplicationContextapplicationContext;
public static ApplicationContext getApplicationContext(){
if(applicationContext ==null){
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
}
return applicationContext;
}
}
方法二:通过实现ApplicationContextAware接口获取步骤一:将代码封装为工具类
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext acx) throws BeansException {
ApplicationContextHolder.applicationContext = acx;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String beanName) {
return (T) ApplicationContextHolder.applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> clazz) {
return (T) ApplicationContextHolder.applicationContext.getBean(clazz);
}
}
步骤二:在Spring的配置文件中也就是applicationContext.xml中配置bean
<bean id="applicationContextHolder" class="com.sheshu.base.util.ApplicationContextHolder"></bean>
- 获取spring容器的方法
- 获取Spring容器的方法
- 获取Spring 容器中bean的方法
- 获取spring容器中bean的方法
- 获取Spring的Bean持有容器对象的方法
- Spring线程获取容器中bean的方法
- Java代码6种方法获取spring 容器的bean
- spring非IOC容器中的对象获取IOC容器中对象的方法
- 在方法中获取spring容器
- 获取父容器的方法
- spring 容器的refresh方法
- java类获取spring容器的bean
- Java类获取spring 容器的bean
- 获取当前的spring容器ApplicationContext 。
- 使用监听获取spring容器的bean
- Java类获取spring 容器的bean
- Java类获取spring 容器的bean
- Java类获取spring 容器的bean
- android_launcher的源码详细分析
- [李景山php]thinkphp核心源码注释|Driver.class.php
- CDN字体引用font-awesome
- 11g 12c nls parameter
- Keepalived原理与实战精讲--VRRP协议
- 获取Spring容器的方法
- css的div垂直居中的方法,百分比div垂直居中
- OSX安装express-generator,并创建Nodejs app
- Linux的内存回收和交换
- [李景山php]thinkphp核心源码注释|Firebird.class.php
- 杭电oj-1321
- C#编程.异常处理(Exception Handling Statements)
- android文件API使用
- [Android] 内存泄漏调试经验分享 (一)