Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

java - how to intercept all requests in spring REST controllers?

I have a bunch of controllers like:

@RestController
public class AreaController {
    @RequestMapping(value = "/area", method = RequestMethod.GET)
    public @ResponseBody ResponseEntity<Area> get(@RequestParam(value = "id", required = true) Serializable id) { ... }
}

and I need to intercept all the requests that reach them,

I created an interceptor like this example:

http://www.mkyong.com/spring-mvc/spring-mvc-handler-interceptors-example/

but it never enters :(

because I'm using only annotations, i don't have a XML to define the interceptor, what I've found its to set it like this:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.test.app")
public class AppConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ControllerInterceptor getControllerInterceptor() {
        ControllerInterceptor c = new ControllerInterceptor();
        return c;
    }

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

}

what am i doing wrong or am i missing something?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

your Interceptor class ControllerInterceptor isn't an application context managed bean. Make sure you put @Component annotation on ControllerInterceptor and add it's package to @ComponentScan. So, let's say your ControllerInterceptor resides in package com.xyz.interceptors like:

package com.xyz.interceptors;  //this is your package

@Component //put this annotation here
public class ControllerInterceptor extends HandlerInterceptorAdapter{
 // code here
}

and your AppConfig becomes:

@ComponentScan(basePackages = { "com.test.app", "com.xyz.interceptors" })
public class AppConfig extends WebMvcConfigurerAdapter {
// ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...