【问题标题】:How to inject interceptor Jar file to spring?如何将拦截器Jar文件注入spring?
【发布时间】:2020-05-08 12:45:11
【问题描述】:

我想通过向 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;
  }

【问题讨论】:

    标签: java spring jar interceptor


    【解决方案1】:

    在运行时,Spring boot 并不真正关心 bean 定义是来自 Jar 还是“直接在项目中”定义(我假设您的意思是在包含带有“main”方法的 Spring boot 应用程序类的工件中。

    但是,由于默认情况下 Spring Boot 具有非常明确的配置扫描策略,因此您可能将配置放在不同的包中,这可能是 Spring Boot 不加载其余模板的原因豆子。

    因此您可以将配置放在将成为 Spring Boot 应用程序的子包的包中。例如:

    package com.foo.bar;
    
    @SpringBootApplication
    public class MyApplication {
       public void main();
    }
    
    

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

    如果您确实想使用不同的包,您应该使用弹簧工厂作为更灵活的替代方案。了解弹簧工厂Here

    万能的:

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

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

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

    package com.abc;
    public class MyConfig {
    
       @Bean
       public RestTemplate restTemplate() {
          // customize with interceptors
       }
    }
    
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多