SpringContextUtil工具类记录
1.SpringContextUtil工具类记录,可在无法注入Bean的时候选择使用,比如在枚举类中实际上是无法使用被IOC管理的Bean的,除非是通过方法传入,现在提供一个工具类解决这个问题(做记录)。
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
setContext(applicationContext);
}
public static void setContext(ApplicationContext applicationContext) {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 适用于springBean使用注解@Service("xxxService")
* 获取接口对象 参数传入xxxService
* @param beanName
* @return
*/
public static Object getBean(String beanName){
return applicationContext.getBean(beanName);
}
/**
*
* @param claz
* @return
*/
public static <T> T getBean(Class<T> claz){
return applicationContext.getBean(claz);
}
}
- 测试方法
public static void main(String[] args) {
UserService userService = SpringContextUtil.getBean(UserService.class);
String res = userService.test();
System.out.println(res);
}