spring boot 普通类获取bean工具类

2019-06-18  文晶 

切记:单元测试时需要需要保证有spring boot上下文
@Component 
public class SpringBeanUtils implements ApplicationContextAware { 
private static ApplicationContext applicationContext;   
public static ApplicationContext getApplicationContext() { 
return applicationContext;  
} 
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtils.applicationContext = applicationContext;  
} 
public static Object getBean(String name){ 
return getApplicationContext().getBean(name);  
} 
public static <T> Object getBean(Class<T> T){ 
return getApplicationContext().getBean(T);  
}
}
511°/5119 人阅读/0 条评论 发表评论

登录 后发表评论