Pee*_*med 3 spring interceptor spring-boot
任何人都可以帮我读取 Spring Boot 拦截器(preHandle方法)中的应用程序属性值吗?
我正在尝试在preHandle. 这个逻辑需要从application.properties文件中获取一些值。我使用@Value注释,但它始终为空。
谢谢
我解决了这个问题。这是详细信息。
解决方案前:
// 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("/**");
}
}
Run Code Online (Sandbox Code Playgroud)
当通过使用“new”关键字创建类来添加拦截器(XYZCustomWebappInterceptor)时,Spring boot将无法理解这些注释。这就是为什么当我在 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
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢大家对我的帮助。
我会建议以下解决方案
@Configuration
public class XYZWebappWebConfig extends WebMvcConfigurerAdapter{
@Autowired
private XYZCustomWebappInterceptor xyzCustomWebappInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(xyzCustomWebappInterceptor).addPathPatterns("/**");
}
}
Run Code Online (Sandbox Code Playgroud)
在实际课程中,您将执行以下操作
// 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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5215 次 |
| 最近记录: |