preface

A friend recently asked me an interesting question: They have a project that uses the JWT token verification and filling component provided by their framework department. The implementation principle is roughly that the token is verified by springboot interceptor. If the token is valid, the token is parsed and the business information map carried by the token is filled into the ThreadLocal. Facilitate subsequent services.

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

The idea was that he would also write an interceptor that would do business padding. The premise here is that the frame section should be executed before the interceptor written by my friend. My friend did this by adding @order annotation to his interceptor, but it didn’t work. So he came to me to discuss this problem.

The abstract question is how do we get springBoot interceptors to execute in the order we want them to execute

Train of thought

Method one: Write a class for your business project that is identical to the framework group

That is, this class and the framework group provided the package name and class name, and then change the class, this implementation principle is to use the class load order

Method 2: using the org. Springframework. Web. Servlet. Config. The annotation. InterceptorRegistration# order ()

However, the order method is not available until Spring 4.3+.

The specific usage is as follows

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

    }
Copy the code

By setting the value of order(), the smaller the value, the higher the priority. The default is not 0

So why configure this? If you dig a little deeper into SpringMVC, interceptor chains will eventually be used

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

That’s what sort is based on that order

conclusion

Solution 2 provided in this article applies to Spring 4.3+ version. Be careful if the version is earlier than spring 4.3+ version.

The demo link

Github.com/lyb-geek/sp…