如何将拦截器 Jar 文件注入 spring?

How to inject interceptor Jar file to spring?

我想通过向 Spring 添加拦截器来拦截 RestTemplate。但是,我想将它实现为一个单独的 JAR 文件,当我将这个 jar 注入任何 spring 项目时,它应该可以工作。

当我直接在项目中实施拦截时,它正在运行。但是,如果我从中创建一个 jar 文件并添加一个项目,它就无法正常工作。

任何帮助将不胜感激。

  public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    ClientHttpResponse response = execution.execute(request, body);
    return response;
  }

  @Bean
  public RestTemplate restTemplate() {
    List<ClientHttpRequestInterceptor> clientHttpRequestInterceptors = new ArrayList();
    clientHttpRequestInterceptors.add(this.loggingInterceptor);
    this.RestTemplate.setInterceptors(clientHttpRequestInterceptors);
    return this.RestTemplate;
  }

在运行时,Spring boot 并不真正关心 bean 定义是来自 Jar 还是定义的 "directly in project"(我假设你的意思是在包含 Spring boot 的工件中使用 "main" 方法应用程序 class。

但是,由于默认情况下 spring 启动有一个定义明确的配置扫描策略,您可能已将配置放在不同的包中,这可能是 spring 引导不加载其余模板 bean。

因此您可以将配置放在包中,该包将成为 spring 引导应用程序的子包。例如:

package com.foo.bar;

@SpringBootApplication
public class MyApplication {
   public void main();
}

然后你可以将其余的模板配置放在com.foo.bar.abc而不是com.foo.xyz

如果你确实想使用不同的包,你应该使用 spring 工厂作为更灵活的选择。了解 spring 个工厂 Here

总计:

  1. 在您的 jar 资源中创建 META-INF/spring.factories 文件

  2. 在该文件中创建 org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.abc.MyConfig

  3. 的映射
  4. 在您的 jar 中创建 com.abc.MyConfig:

package com.abc;
public class MyConfig {

   @Bean
   public RestTemplate restTemplate() {
      // customize with interceptors
   }
}

如果您发现它与其他自动配置冲突,您可以使用 @AutoConfigureAfter 注释。