【发布时间】: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