【问题标题】:How can i Write a custom Enable annotation for Interceptor in Spring boot app?如何在 Spring Boot 应用程序中为拦截器编写自定义启用注释?
【发布时间】:2017-05-12 20:43:22
【问题描述】:

是否可以编写自定义启用注释来启用 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中实现吗?如果是,请告诉我怎么做。

【问题讨论】:

  • 我的例子回答了你的问题吗?

标签: java spring spring-boot


【解决方案1】:

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

public CustomInterceptor extends HandlerInterceptor {}

让你想要的 Interceptor 实现这个接口,并使用ApplicationContext 来确定哪些 Spring bean 实现了这个接口:

@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 接口的bean,然后检查它们的注释。您可以通过这种方式检查 bean 的注释:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    相关资源
    最近更新 更多