今天在處理系統操作日誌記錄的時候,想在filter中引用Service並操作數據庫。
(*注:有人可能會說我爲什麼不選用aop,也有人會說爲什麼不採用攔截器,非要選擇過濾器,我只能說呵呵【我是菜鳥】)
廢話不多說。
private WriteSyslog writeSyslog; private FilterConfig config; @Override public void init(FilterConfig arg0) throws ServletException { config = arg0; ServletContext sc = arg0.getServletContext(); WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(sc); if (cxt != null && cxt.getBean(WriteSyslog.class) != null && writeSyslog == null) { writeSyslog = (WriteSyslog) cxt.getBean(WriteSyslog.class); } }
然後就可以調用了...
具體爲什麼請仔細閱讀以下博主的描述:
https://blog.csdn.net/chl191623691/article/details/78657638
最後說一下我嘗試失敗的幾種:
① 我嘗試了這個兄弟的寫法:(不滿意)
② 我採用了ApplicationContextUtils工具類的調用bean方式:(不滿意)
@Component public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext ctx) throws BeansException { if (SpringContextUtil.applicationContext == null) { SpringContextUtil.applicationContext = ctx; } } /** * 獲取applicationContext */ public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 通過name獲取 Bean * * @param name * @return */ public static Object getBean(String name) { return getApplicationContext().getBean(name); } /** * 通過class獲取Bean * * @param clazz * @param <T> * @return */ public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); } /** * 通過name,以及Clazz返回指定的Bean * * @param name * @param clazz * @param <T> * @return */ public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); } }
③ 還有這種的(也失敗)
感謝各位博主的技術方向,讓我解決了我的問題。