今天在自己定義的filter中,想要直接注入spring容器的其它bean進行操作,發現不能正常的注入:
原因:web容器加載順序導致, 加載順序是listener——filter——servlet,當項目啟動時,filter先於servlet初始化, 而Spring中默認bean的初始化是在Servlet后進行的,所以會注入失敗
解決辦法:接下來編寫一個SpringUtils進行手動注入bean
1 @Component 2 public class SpringUtils implements ApplicationContextAware{ 3 private static ApplicationContext applicationContext; 4 5 @Override 6 public void setApplicationContext(ApplicationContext applicationContext) 7 throws BeansException { 8 if (SpringUtils.applicationContext == null) { 9 SpringUtils.applicationContext = applicationContext; 10 } 11 12 } 13 14 public static ApplicationContext getApplicationContext() { 15 return applicationContext; 16 } 17 18 //根據name 19 public static Object getBean(String name) { 20 return getApplicationContext().getBean(name); 21 } 22 23 //根據類型 24 public static <T> T getBean(Class<T> clazz) { 25 return getApplicationContext().getBean(clazz); 26 } 27 28 public static <T> T getBean(String name, Class<T> clazz) { 29 return getApplicationContext().getBean(name, clazz); 30 } 31 }
在需要使用的filter中,直接使用工具類拿到相應的對象