如何向春季注入拦截器Jar文件?

问题描述 投票:0回答:1

我想通过向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个回答
1
投票

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

但是,由于默认情况下,Spring Boot的配置扫描策略定义得非常好,因此可能会将配置放置在其他软件包中,这可能是Spring Boot不会加载其余模板Bean的原因。

因此,您可以将配置放入Spring Boot应用程序的子软件包中。例如:

package com.foo.bar;

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

然后您可以将其余模板配置放置在com.foo.bar.abc中,但不能放置在com.foo.xyz中>

如果您确实想使用其他软件包,则应使用spring工厂作为更灵活的选择。了解有关弹簧工厂Here

全能:

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

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.