spring[2]-ApplicationContextAware
通过ApplicationContextAware,Spring容器会自动把上下文环境对象调用ApplicationContextAware接口中setApplicationContext方法,可以通过这个上下文环境对象得到Spring容器中的Bean。
- 静态方法使用springbean无法通过@Autowried注入
- 线程内无法使用springbean
- 此时,可以通过ApplicationContextAware来实现
SpringContextHolder.java
package com.ApplicationContextAware;//import org.apache.commons.lang.Validate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;/*** ApplicationContextAware 通过它Spring容器会自动把上下文环境对象调用ApplicationContextAware接口中的setApplicationContext方法。* 我们在ApplicationContextAware的实现类中,就可以通过这个上下文环境对象得到Spring容器中的Bean。** 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.*/
@Component
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware {private static ApplicationContext context;// 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.@Overridepublic void setApplicationContext(ApplicationContext applicationContext)throws BeansException {context = applicationContext;}// 取得存储在静态变量中的ApplicationContext.public static ApplicationContext getApplicationContext() {//assertContextInjected();return context;}// 清除applicationContext静态变量.public static void clearHolder() {context = null;}// 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.public static <T> T getBean(Class<T> requiredType) {//assertContextInjected();return (T) getApplicationContext().getBean(requiredType);}// 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.public static <T> T getBean(String name) {assertContextInjected();return (T) getApplicationContext().getBean(name);}//判断application是否为空public static void assertContextInjected() {Validate.isTrue(context == null, "application未注入 ,请在springContext.xml中注入SpringHolder!");}}
使用案例 - 线程调用
UserService userService = SpringContextHolder.getBean(UserService.class);
使用案例 - 静态方法
private static UserService userService = SpringContextHolder.getBean(UserService.class);
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
