如何在Spring启动应用程序中为Interceptor编写自定义启用注释?

时间:2016-12-28 14:36:33

标签: java spring spring-boot

是否可以编写自定义启用注释以启用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);
    }
}

这可以在春季靴子中实现吗?如果有,请告诉我如何做到。

1 个答案:

答案 0 :(得分: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;
}