[英]Can I use an instance of a WebMvcConfigurer in another module?
I've written an interceptor to generate service logs for a SpringBoot Java Rest API.我编写了一个拦截器来为 SpringBoot Java Rest API 生成服务日志。 I have the code below to define the custom WebMvcConfigurer:我有下面的代码来定义自定义 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.我想在不同的模块中使用这个 InterceptorConfig。 Can I package it and use it or do I need to define it in each module?我可以打包并使用它还是需要在每个模块中定义它?
I suppose with "other modules" you are asking if you could make that code available to other spring boot applications too?我想对于“其他模块”,您是在问是否可以使该代码也可用于其他 Spring Boot 应用程序?
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.如果是这种情况 - 那么:是的,您可以将其打包在 jar 中,并将其作为依赖项添加到所有其他模块中。 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 .简而言之,您需要做的是创建自己的外部工件(这通常通过 maven 或 gradle 完成。您为共享代码创建一个新的 maven 项目。它需要依赖于一些基础库,以便您有你的@Configuration
注释。把你的类放在那个项目中,并创建一个文件src/main/resources/META-INF/spring.factories
文件。 在那里你需要指向那个类。
Then you build that project and upload the resulting jar to a package repository.然后构建该项目并将生成的 jar 上传到包存储库。 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.在启动时,Spring boot 会找到spring.factories
文件并自动包含在其初始化中提到的类。
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 . Spring 有关于这个用例的很好的文档,他们也有一个演示项目来展示这个扩展机制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.