gpt4 book ai didi

java - 如何在 Spring boot 应用程序中为拦截器编写自定义启用注释?

转载 作者:行者123 更新时间:2023-11-30 06:58:31 26 4
gpt4 key购买 nike

是否可以编写自定义启用注释来为 Spring Boot 应用程序启用拦截器。

这是我的代码,

配置

@Configuration
public class CustomConfig extends WebMvcConfigurerAdapter {

@Autowired
CustomInterceptor interceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interceptor);
}

}

拦截器

@Component
public class CustomInterceptor implements HandlerInterceptor {

@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {

System.err.println("Executed!!!afterCompletion");

}

@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
System.err.println("Executed!!!postHandle");

}

@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
// TODO Auto-generated method stub
return true;
}

}

自定义注释

@Documented
@Retention(RUNTIME)
@Target(TYPE)
@Import(CustomConfig.class)
public @interface EnableCustomConfig {

}

我想仅当此注释时启用此拦截器

@EnableCustomConfig

出现在主类中,

@SpringBootApplication
@EnableAutoConfiguration
@EnableCustomConfig
public class CustomEnableApplication {

public static void main(String[] args) {
SpringApplication.run(CustomEnableApplication.class, args);
}
}

这可以在 Spring Boot 中实现吗?如果是的话,请告诉我如何做。

最佳答案

这里有几个选项。首先,我想我会完全跳过注释。您可以简单地扩展接口(interface):

public CustomInterceptor extends HandlerInterceptor {}

让您想要的拦截器实现此接口(interface),并使用 ApplicationContext 来确定哪些 Spring bean 实现此接口(interface):

@Autowired
private ApplicationContext applicationContext;

@Override
public void addInterceptors(InterceptorRegistry registry) {
Map<String, CustomInterceptor> interceptors = applicationContext.getBeansOfType(CustomInterceptor.class);
for(CustomInterceptor interceptor : interceptors.values()){
registry.addInterceptor(interceptor);
}
}

如果您决定使用注释,则可以使用与上述逻辑基本相同的逻辑。您将获得实现 HandlerInterceptor 接口(interface)的所有 bean,然后检查它们的注释。您可以通过以下方式检查 bean 的注释:

public boolean isAnnotatedWithMyAnnotation(Class clazz){
return clazz.getAnnotation(EnableCustomConfig.class) == null ? false : true;
}

关于java - 如何在 Spring boot 应用程序中为拦截器编写自定义启用注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41364195/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com