Springboot 攔截器無法通過自動注入注入Bean
1.問題
使用Springboot的攔截器HandlerInterceptor介面
無法通過@Autowired自動注入Bean
2.解決方式
通過applicationContext來擷取bean
private VisitInfoRepo visitInfoRepo() { return (VisitInfoRepo) ApplicationContextUtils.applicationContext.getBean("visitInfoRepo");}
應用程式上下文工具類
public class ApplicationContextUtils { public static ApplicationContext applicationContext; /** * 通過名稱擷取bean */ public static Object get(String name) { return applicationContext.getBean(name); } /** * 通過類型擷取bean */ public static Object get(Class<?> clazz) { return applicationContext.getBean(clazz); } /** * 判斷某個bean是不是存在 */ public static boolean has(String name) { return applicationContext.containsBean(name); }}
在程式初始化的時候註冊應用程式上下文
import com.simply.zuozuo.util.ApplicationContextUtils;import lombok.Data;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.lang.Nullable;import org.springframework.stereotype.Component;/** * @author Created by 譚健 on 2018/4/13 0013. 星期五. 11:29. * © All Rights Reserved. */@Slf4j@Component@Datapublic class ApplicationContextAwareImpl implements ApplicationContextAware { /** * 實現該介面用來初始化應用程式上下文 * 該介面會在執行完畢@PostConstruct的方法後被執行 * <p> * 接著,會進行Mapper地址掃描並載入,就是RequestMapping中指定的那個路徑 * * @param applicationContext 應用程式上下文 * @throws BeansException beans異常 */ @Override public void setApplicationContext(@Nullable ApplicationContext applicationContext) throws BeansException { log.info("應用程式上下文 : [{}]", "開始初始化"); ApplicationContextUtils.applicationContext = applicationContext; ApplicationContext context = ApplicationContextUtils.applicationContext; log.info("應用程式上下文 getId : [{}]", applicationContext.getId()); log.info("應用程式上下文 getApplicationName : [{}]", applicationContext.getApplicationName()); // log.info("應用程式上下文 getAutowireCapableBeanFactory : [{}]",applicationContext.getAutowireCapableBeanFactory()); // log.info("應用程式上下文 getDisplayName : [{}]",applicationContext.getDisplayName()); // log.info("應用程式上下文 getParent : [{}]",applicationContext.getParent()); log.info("應用程式上下文 getStartupDate : [{}]", applicationContext.getStartupDate()); // log.info("應用程式上下文 getEnvironment : [{}]",applicationContext.getEnvironment()); log.info("應用程式上下文 : [{}]", "初始化完成"); }}