Spring Boot中拦截器中使用@Value无效

场景

在使用Spring Boot框架时,很经常会使用到拦截器。可是,有时候我们会遇到在拦截器使用@Value注解来获取配置文件中的配置参数获取失败,一直都是为null的情况。

以往

以往的配置如下:

/**
 * 添加拦截器配置
 * @author Kellan_Song
 * @createTime 2018年3月27日
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
	@Override
	    public void addInterceptors(InterceptorRegistry registry) {
	        // 多个拦截器组成一个拦截器链
	        // addPathPatterns 用于添加拦截规则
	        // excludePathPatterns 用户排除拦截
	        //new ParamInterceptor()是一个参数拦截器拦截 /api/接口的参数
	        registry.addInterceptor(new ParamInterceptor()).addPathPatterns("/api/**");
	        WebMvcConfigurer.super.addInterceptors(registry);
	    }

}

这种配置在网上是最多人建议的,但正是这种配置方式导致在拦截器中使用@value为null。(像我技术这么菜的人,真的找了很久的原因,才发现此处有问题)。

接下来给大家看看使用@Value获取配置不为null的配置方式:

/**
 * 添加拦截器配置
 * @author Kellan_Song
 * @createTime 2018年3月27日
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

	/**
	 * 添加拦截器的方式,可直接new一个对象,
	 * registry.addInterceptor(new ParamInterceptor()),
	 * 但通过手动new出来的拦截器中,无法使用@Autowired 和 @Value 加载对象和配置文件参数。
	 *
	 * 所以需要在添加拦截器此处,通过@Bean 注解,意味着将这个对象
	 * 交给spring管理。那么该拦截器才可以使用@Value等spring管理的注解
	 * @return
	 */
	@Bean
	public ParamInterceptor paramInterceptor() {
		return new ParamInterceptor();
	}

	@Override
	    public void addInterceptors(InterceptorRegistry registry) {
	        // 多个拦截器组成一个拦截器链
	        // addPathPatterns 用于添加拦截规则
	        // excludePathPatterns 用户排除拦截
	        //paramInterceptor()是一个参数拦截器拦截 /api/接口的参数
	        registry.addInterceptor(paramInterceptor()).addPathPatterns("/api/**");
	        WebMvcConfigurer.super.addInterceptors(registry);
	    }

}

这种配置方式,区别就是将之前手动new出来的拦截器,转换成通过@Bean注解创建的形式登记到拦截器登记中心中。

结论

原因就是上面所说的,如果通过手动new出来的对象登记上去,那么这个对象就不由spring管理。而通过@Bean注解,将该对象放到spring的Ioc容器中管理,那么该对象才可以使用spring的注解@Value来获取配置信息。

你可能感兴趣的:(spring-boot)