之前的项目是控制台项目没有引入springboot相关的依赖,后续因为想更好提供接口给客户方进行调用,将控制台程序更改成springboot项目,引入springboot后,之前普通类中想调用spring ioc容器中的bean,因为普通类已经脱离了spring boot ioc范围,所有需要通过别的方式来解决。了解springboot ioc容器原理中,我们知道,在spring的整体框架中存在很多以Aware结尾的接口,Aware接口的含义是 “感知”,类似applicationcontextaware 就是感知applicationcontext,只要继承该接口就可以在该类中使用applicationcontext。
//加入component注解,让spring扫描到该bean
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
public SpringUtil() {
}
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
if (applicationContext == null) {
applicationContext = arg0;
}
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static void setAppCtx(ApplicationCo