我正在開發一個 jar 庫并嘗試將一個攔截器從外部 jar 庫注入到應用程式。
例如:
外部庫
MyExternalInterceptor.java
public class MyExternalInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// Do something
}
}
我嘗試在外部庫中使用 AOP,但它不起作用。
攔截器Aspect.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;
}
在使用該庫的應用程式中:
應用
我的配置.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 */
}
}
有什么方法可以將外部庫中的攔截器注入到 App 中?
我知道這個問題非常晦澀(對此感到抱歉),但是您能給我任何建議或提示以使其發揮作用嗎?
感謝任何閱讀我的問題的人:)
(我更新了更多細節以進行澄清)
uj5u.com熱心網友回復:
概括
WebMvcConfigurer在客戶端和庫端使用,而不是WebMvcConfigurationSupport- 不需要 AoP
我使用WebMvcConfigurer而不是WebMvcConfigurationSupport更改一些代碼,如下所示:
外部庫
MyExternalInterceptor.java
- 和之前一樣
介面Aspect.java
- 不再需要它
MyExternalLibConfiguration.java
@Configuration
public class MyExternalLibConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyExternalInterceptor());
}
}
應用程式(客戶端)
我的配置.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 */
}
}
就這樣!正如M. Deinum在評論中所說,一切都運行良好。
再次感謝 Deinum!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/428754.html
