- 新建一个类,来装Spring的上下文
public class SpringContext {
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static void setApplicationContext(ApplicationContext applicationContext) {
SpringContext.applicationContext = applicationContext;
}
}
- 新建一个系统初始化的监听器,用来将上下文装到我们的SpringContext
public class InitListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(sc);
SpringContext.setApplicationContext(context);
new Thread(new KafkaConsumer("cache-message")).start();
}
public void contextDestroyed(ServletContextEvent sce) {
}
}
同时也给这个InitListener类初始化到Spring
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public ServletListenerRegistrationBean servletListenerRegistrationBean() {
ServletListenerRegistrationBean servletListenerRegistrationBean =
new ServletListenerRegistrationBean();
servletListenerRegistrationBean.setListener(new InitListener());
return servletListenerRegistrationBean;
}
- 在业务逻辑类中调用即可
CacheService cacheService=(CacheService) SpringContext.getApplicationContext()
.getBean("cacheService");