foreword

Recently a friend and I asked a very interesting question: they have a project that uses the jwt token verification fill component provided by their framework department. The implementation principle is probably to verify the token through the springboot interceptor. If the token is valid, it will be parsed. token, fills the business information map carried by the token into threadlocal, which is convenient for subsequent business use.

The friend's problem is that he wants to extend some business fields to the business map in this threalocal, but because this component is not developed by the friend's department, he can't change the source code, but only through extension.

His idea is that he also writes an interceptor and fills in business in this interceptor. There is a premise here that the execution time of the framework department must be before the interceptor written by the friend. The friend's method is to add the @Order annotation to the interceptor written by him, but it is found that it does not work. So come to me to discuss this issue.

The abstracted question is how to make the execution order of springboot interceptors execute in the order we want as mentioned in the title

ideas

Method 1: Write a class exactly the same as the framework group for your own business project

That is, the package name and class name provided by the class and the framework group are the same, and then the class is changed. The implementation principle is to use the loading order of the classes.

Method 2: Use org.springframework.web.servlet.config.annotation.InterceptorRegistration#order()

However, this order method is only provided after the spring 4.3+ version.

The specific use form is as follows

 @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(helloHandlerInterceptor).addPathPatterns("/**").order(100);
        registry.addInterceptor(otherHelloHandlerInterceptor).addPathPatterns("/**").order(-1);

    }

By configuring the value of order(), the smaller the value, the higher the priority. Unworthy default is 0

So why configure this, if you have a little deeper understanding of springmvc, the interceptor chain will eventually be used

protected List<Object> getInterceptors() {
        return this.registrations.stream()
                .sorted(INTERCEPTOR_ORDER_COMPARATOR)
                .map(InterceptorRegistration::getInterceptor)
                .collect(Collectors.toList());
    }

Sorting is based on this order

Summarize

The second solution provided in this article is applicable to spring 4.3+ version. Please be careful if it is lower than this version.

demo link

https://github.com/lyb-geek/springboot-learning/tree/master/springboot-interceptor-order


linyb极客之路
336 声望193 粉丝