使用springboot開發(fā)時(shí)源哩,有一個(gè)需求是在過濾器filter中判斷用戶登錄的信息鞋吉,于是我寫了一個(gè)UserService,并且在過濾器中實(shí)現(xiàn)自動(dòng)裝配(@Autowired)鸦做。使用springboot自帶的服務(wù)器啟動(dòng)時(shí)沒有問題,但是使用外部的Tomcat啟動(dòng)時(shí)就不能實(shí)現(xiàn)自動(dòng)裝配了谓着,報(bào)NullPointerException錯(cuò)誤泼诱。搞了半天不知道什么原因,我就想到用ApplicationContext的方式來獲取UserService漆魔,具體如下:
- 新建SpringContext類(這個(gè)類要和springboot啟動(dòng)類放一起):
@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);