listener中@Autowired無法注入bean的一種解決方法


背景:使用監聽器處理業務,需要使用自己的service方法;

錯誤:使用@Autowired注入service對象,最終得到的為null;

原因:listener、fitter都不是Spring容器管理的,無法在這些類中直接使用Spring注解的方式來注入我們需要的對象。

解決:寫一個bean工廠,從spring的上下文WebApplicationContext 中獲取。

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
* @ClassName: SpringJobBeanFactory*/
@Component
public class SpringJobBeanFactory implements ApplicationContextAware {

    
    private static ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringJobBeanFactory.applicationContext=applicationContext;
        
    }
     public static ApplicationContext getApplicationContext() {
            return applicationContext;
    }
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
            if (applicationContext == null){
                return null;
            }
            return (T)applicationContext.getBean(name);
      }
    
    public static <T> T getBean(Class<T>  name) throws BeansException {
            if (applicationContext == null){
                return null;
            }
            return applicationContext.getBean(name);
      }
}

監聽器里獲取service,使用getBean(XXX.class)

@Override
    public void sessionDestroyed(HttpSessionEvent event) {
        logger.debug("session銷毀了");
        UserCountUtils.subtract();//在線人數-1

        HttpSession session = event.getSession();// 獲得Session對象
        ServletContext servletContext = session.getServletContext();

        Account acc = (Account) session.getAttribute("user");
        if(acc!=null){
            @SuppressWarnings("unchecked")
            Map<String, String> loginMap = (Map<String, String>) servletContext.getAttribute("loginMap");
            loginMap.remove(acc.getUserName());
            servletContext.setAttribute("loginMap", loginMap);
            session.removeAttribute("user");
            acc.setOnlineState(false); //注銷成功修改用戶在線狀態為 離線
            //WebApplicationContext appctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
            //AccountService accountService = appctx.getBean(AccountService.class);
            AccountService accountService = SpringJobBeanFactory.getBean(AccountService.class);
            accountService.updateAccount(acc);
            logger.debug(acc.getUserName()+"用戶注銷!");
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM