使用springboot開發(fā)時,有一個需求是在過濾器filter中判斷用戶登錄的信息,于是我寫了一個UserService,并且在過濾器中實現(xiàn)自動裝配(@Autowired)。使用springboot自帶的服務器啟動時沒有問題,但是使用外部的Tomcat啟動時就不能實現(xiàn)自動裝配了,報NullPointerException錯誤。搞了半天不知道什么原因,我就想到用ApplicationContext的方式來獲取UserService,具體如下:
- 新建SpringContext類(這個類要和springboot啟動類放一起):
@Component
@Lazy(false)
public class SpringContext implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
- 使用:
//通過class獲得bean
UserService userService= SpringContext.getBean(UserService.class);
//通過name獲得bean
UserService userService= SpringContext.getBean("userService");
//通過name,以及Clazz返回指定的Bean
UserService userService= SpringContext.getBean("userService",UserService.class);