Spring启动拦截器

时间:2017-04-24 15:03:08

标签: spring spring-boot interceptor

有没有人可以帮我看一下Spring Boot拦截器中的应用程序属性值(preHandle方法)?

我试图在preHandle中写一些逻辑。此逻辑需要从application.properties文件中获取一些值。我使用@Value注释,但它始终为null。

谢谢

2 个答案:

答案 0 :(得分:2)

我会建议以下解决方案

   @Configuration
public class XYZWebappWebConfig extends WebMvcConfigurerAdapter{



@Autowired
private XYZCustomWebappInterceptor xyzCustomWebappInterceptor;

 @Override
 public void addInterceptors(InterceptorRegistry registry){

    registry.addInterceptor(xyzCustomWebappInterceptor).addPathPatterns("/**");
   }

}

在实际课程中,您将执行以下操作

// Custom interceptor class
@Component
public class XYZCustomInterceptor implements HandlerInterceptor{
@Value("${JWT.secret}")
private String jwtSecret;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse 
                           response, Object arg2) throws Exception {
//use the secret key
}
}

答案 1 :(得分:0)

我解决了这个问题。这是详细信息。

解决方案之前:

// Custom interceptor class
public class XYZCustomInterceptor implements HandlerInterceptor{
@Value("${JWT.secret}")
private String jwtSecret;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse 
                               response, Object arg2) throws Exception {

 // I am using the jwtSecret in this method for parsing the JWT
 // jwtSecret is NULL

  }
}


 //To Register (another class)

 @Configuration
 public class XYZWebappWebConfig extends WebMvcConfigurerAdapter{

 @Override
 public void addInterceptors(InterceptorRegistry registry){

    registry.addInterceptor(new                         
                 XYZCustomWebappInterceptor()).addPathPatterns("/**");
   }

}

当通过使用'new'关键字创建类来添加拦截器(XYZCustomWebappInterceptor)时,Spring启动将无法理解注释。这就是为什么当我在XYZCustomWebappInterceptor中读取这些值(来自application.properties的jwtSecret)时,它为空。

我是如何解决的:

//Read those properties values in this class and pass it to interceptor's 
//constructor method. 

 @Configuration
 public class XYZWebappWebConfig extends WebMvcConfigurerAdapter{

 @Value("${JWT.secret}")
 private String jwtSecret;

 @Override
 public void addInterceptors(InterceptorRegistry registry){

    registry.addInterceptor(new                         

    XYZCustomWebappInterceptor(jwtSecret)).addPathPatterns("/**");
   }

}


// Custom interceptor class
public class XYZCustomInterceptor implements HandlerInterceptor{

private String jwtSecret;

RbsCustomWebappInterceptor(String secret){
    this.jwtSecret = secret;
}

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse 
                               response, Object arg2) throws Exception {


 // I am using the jwtSecret in this method for parsing the JWT
 // Now, jwtSecret is NOT NULL

  }
}

感谢所有人帮助我。