Home > Software design >  Can I use an instance of a WebMvcConfigurer in another module?
Can I use an instance of a WebMvcConfigurer in another module?

Time:11-11

I've written an interceptor to generate service logs for a SpringBoot Java Rest API. I have the code below to define the custom WebMvcConfigurer:

package com.gem.common.interceptors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Autowired
    LoggerInterceptor logInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(logInterceptor);
    }
}

I'd like to use this InterceptorConfig across different modules. Can I package it and use it or do I need to define it in each module?

CodePudding user response:

I suppose with "other modules" you are asking if you could make that code available to other spring boot applications too?

If that's the case - then: yes you can package it in a jar and add it as a dependency to all your other modules. I'll post the way to do this just below, however - just to warn you - if it's just for that simple class, the solution is not going to be worth it.

In short, what you'd need to do is to create your own external artifact (this usually is done via maven or gradle. You create a new maven project for your shared code. It will need to depend on some base libraries so that you have your @Configuration annotation available. Put your class as described in that project, and create a file src/main/resources/META-INF/spring.factories file. There you'll need to point to that class.

Then you build that project and upload the resulting jar to a package repository. Once that's done, you can add it as a dependency to your project. At startup, Spring boot will find the spring.factories file and automatically include the classes that are mentioned there in its initialization.

Please also note, that this is just a high level explanation and you will need more details. Spring has good documentation on this use case and they also have a demo project to show this extension mechanism.

  • Related