Search code examples
javaspringjarinterceptor

How to inject interceptor Jar file to spring?


I would like to intercept RestTemplate by adding interceptor to Spring. However, I would like to implement this as a separated JAR file and when I inject this jar to any spring project, it should be worked.

When I implement interception in directly to project it is working. However, if I create a jar file from it and add a project it is not working.

Any help will be appreciated.

  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;
  }

Solution

  • In runtime, Spring boot doesn't really care whether the bean definition comes from the Jar or defined "directly in project" ( I assume you mean in the artifact that contains Spring boot application class with a "main" method.

    However, since by default spring boot has a very well defined policy of configuration scanning, its possible that you've placed the configuration in a different package, and that could be a reason that spring boot doesn't load the rest template bean.

    So you can place the configuration in package that will be a subpackage of spring boot application. For example:

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

    Then you can place the rest template configuration in com.foo.bar.abc but not in com.foo.xyz

    If you do want to use different package you should use spring factories as a more flexible alternative. Read about spring factories Here

    All-in-all:

    1. Create META-INF/spring.factories file in resources of your jar

    2. In that file create a mapping of org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.abc.MyConfig

    3. Create com.abc.MyConfig in your jar:

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

    If you see that it clashes with other autonfiguration you can use @AutoConfigureAfter annotation.