wuquegongzi / template

脚手架
1 stars 0 forks source link

此处获取env时,为null #1

Open zxyle opened 2 years ago

zxyle commented 2 years ago

https://github.com/swleon/template/blob/5655f437ca4697445f678046af23214c95310c1e/springboot-web-demo/src/main/java/com/leon/config/interceptor/AllowCrossDomainInterceptor.java#L27

当进入拦截器的preHandle方法,获取env时为null.

我尝试这么写

@Component
public class AllowCrossDomainInterceptor implements HandlerInterceptor {

    private final Environment env;

    @Autowired
    public AllowCrossDomainInterceptor(Environment env) {
        this.env = env;
    }
}

使用的时候将env传入到构造函数里

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Autowired
    Environment env;

    /**
     * 拦截器
     * addPathPatterns     用于添加拦截规则
     * excludePathPatterns 用户排除拦截
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AllowCrossDomainInterceptor(env))
                .addPathPatterns("/**");

    }
}
wuquegongzi commented 2 years ago

https://github.com/swleon/template/blob/5655f437ca4697445f678046af23214c95310c1e/springboot-web-demo/src/main/java/com/leon/config/interceptor/AllowCrossDomainInterceptor.java#L27

当进入拦截器的preHandle方法,获取env时为null.

我尝试这么写

@Component
public class AllowCrossDomainInterceptor implements HandlerInterceptor {

    private final Environment env;

    @Autowired
    public AllowCrossDomainInterceptor(Environment env) {
        this.env = env;
    }
}

使用的时候将env传入到构造函数里

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Autowired
    Environment env;

    /**
     * 拦截器
     * addPathPatterns     用于添加拦截规则
     * excludePathPatterns 用户排除拦截
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AllowCrossDomainInterceptor(env))
                .addPathPatterns("/**");

    }
}
截屏2021-12-28 下午5 55 21

springboot 版本2.4.3,没有空指针问题,其他版本的话,如果有问题,可以采用构造函数解决