Dims
Dims

Reputation: 51239

Is it possible to set interceptor with annotation in Spring?

I am trying to stay declarative, convention-base and XML-less.

So, I have no web.xml, and I have no context configuration XMLs. Unfortunately, Google is spammed with old-fashion Spring examples and it is impossible to find modern answer.

My question is: is it possible to declare interceptor with annotations in Spring? Apparently it would be possible to do the same way as it done with controllers (controller class is annotated with @Controller and it's methods -- with @RequestMapping).

The best way I found is here https://stackoverflow.com/a/16706896/258483

Unfortunately, it is not declarative.

Upvotes: 3

Views: 2378

Answers (1)

turboemu
turboemu

Reputation: 184

Using Java configuration and the @Configuration annotation it looks like you create an interceptor and register it as described here. It's not as simple as annotating a class as an interceptor but may still adhere to your stipulations.

EDIT:

In java configuration class, we need to extend WebMvcConfigurerAdapter. To add our interceptor, we override WebMvcConfigurerAdapter. addInterceptors() method. Find the code snippet.

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LoggingInterceptor());
    registry.addInterceptor(new TransactionInterceptor()).addPathPatterns("/person/save/*");
}

Upvotes: 1

Related Questions