docker實戰 環境搭建

  • 新建一個類,來裝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"); 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章