第一步:实现 ApplicationContextAware接口
第二步:给类加上注解 @Component 让spring识别并且注入
第三步:定义好静态的 ApplicationContext ,在ApplicationContextAware实现的 setApplicationContext赋值过去;
后面就是自己根据自己的需求定义获取bean的接口
如:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Created by Lee on 2018/5/7.
*/
@Component
public class DemoApplicationContextHelper implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("我已经注入啦");
context=applicationContext;
}
public static <T> T getBean(Class<T> tClass){
if(null==context){
return null;
}
return context.getBean(tClass);
}
}
注:如果项目启动后ApplicationContext为空的话,可能是项目配置了全局spring bean的懒加载功能,这时候就需要在类上加个注解: @Lazy(value=false)