问题:项目启动报空指针
定位:新增filter中init方法使用getbean控制
解决:在新增filter上加注解
@DependsOn({"applicationContextUtils"})
@Component
@DependsOn({"applicationContextUtils"})//此处解决空指针问题
public class XssFilter implements Filter{
@Autowired
private MultipartResolver multipartResolver=null;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//注入bean
multipartResolver=(MultipartResolver) ApplicationContextUtils.getApplicationContext().getBean("multipartResolver",MultipartResolver.class);
}
}
package com.bonc.ds.web.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import java.util.Locale;
//对Spring容器进行各种上下文操作的工具类
@Configuration
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
ApplicationContextUtils.context = context;
}
public static ApplicationContext getApplicationContext(){
return context;
}
//根据Bean名称获取Bean对象
public static Object getBean(String beanName){
return context.getBean(beanName);
}
public static Object getMassage(String key){
return context.getMessage(key, null, Locale.getDefault());
}
}
分析:
ApplicationContextUtils是否在Configuration的Bean初始化之前初始化是未知的。
用到的@DependsOn注解,先把SpringContextUtils注册到Spring容器里面
注解含义就是组件A要依赖于另一个组件B,也就是说被依赖的组件B会比组件A先注册到Spring容器中