I’m developing a jar library and trying to inject an interceptor from external jar library to Application.
For example:
External Lib
MyExternalInterceptor.java
public class MyExternalInterceptor implements HandlerInterceptor { @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // Do something } }
I tried to using AOP in external libs but it’s not working.
InterceptorAspect.java
@Around("execution(* org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.addInterceptors(..))") public Object aspect(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { // Tried to inject MyExternalInterceptor here Object result = proceedingJoinPoint.proceed(); return result; }
In Application using that lib:
Application
MyConfiguration.java
@Configuration public MyConfiguration extends WebMvcConfigurationSupport { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new SpringTestInterceptor()); // client's own interceptor /* Add MyExternalInterceptor not explicitly but implicitly using AOP or other things */ } }
Is there any way to inject an interceptor from external lib to App?
I know the question is very obscure (sorry for that), but could you give me any advice or hint to make it work?
Thank you for anyone who read my question 🙂
(I updated few more details for clarification)
Advertisement
Answer
Summary
- Use
WebMvcConfigurer
in both Client and library side instead ofWebMvcConfigurationSupport
- AoP is not needed
I use WebMvcConfigurer
instead of WebMvcConfigurationSupport
and change some codes like below:
External Lib
MyExternalInterceptor.java
- Same as before
InterfaceAspect.java
- Don’t needed it anymore
MyExternalLibConfiguration.java
@Configuration public class MyExternalLibConfiguration implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyExternalInterceptor()); } }
Application (client)
MyConfiguration.java
@Configuration public MyConfiguration implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new SpringTestInterceptor()); // client's own interceptor /* No need to add MyExternalInterceptor in here */ } }
That’s all! Everything is working well as M. Deinum said in comment.
Thank you again Deinum!