How to get the bean of the interceptor in spring mvc

For example, Test2Interceptor wants to get TestInterceptor to operate
<mvc:interceptors>
	<mvc:interceptor>
		<mvc:mapping path="/**"/>
		<bean class="com.xxx.TestInterceptor">	
		</bean>
	</mvc:interceptor>
        <mvc:interceptor>
		<mvc:mapping path="/**"/>
		<bean class="com.xxx.Test2Interceptor">		
		</bean>
	</mvc:interceptor>
</mvc:interceptors>

public class TestInterceptor implements HandlerInterceptor {

}

public class Test2Interceptor implements HandlerInterceptor,ApplicationContextAware {
        private ApplicationContext applicationContext;
        public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object object) throws Exception {
Map<String,MappedInterceptor> map = applicationContext.getBeansOfType(MappedInterceptor.class);
		for(MappedInterceptor m : map.values()) {
			if(m.getInterceptor() instanceof TestInterceptor) {
				System.out.println(m.getInterceptor());
			}
		}
        }
       public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
		
	}
}

It turns out that spring mvc puts the beans configured by <mvc:interceptors> into the MappedInterceptor instance.
Let look at the MappedInterceptor source code.
public final class MappedInterceptor {

	private final String[] includePatterns;

	private final String[] excludePatterns;

	private final HandlerInterceptor interceptor;
//omit
}

Here it is concluded that MappedInterceptor holds HandlerInterceptor instance objects, and HandlerInterceptor is the interface to be practiced by the interceptor we just wrote.
So we understand, you're done.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326925178&siteId=291194637