[英]Why should I use constructor if I can initialize instance variable another way
[英]Can I use an instance of a WebMvcConfigurer in another module?
我編寫了一個攔截器來為 SpringBoot Java Rest API 生成服務日志。 我有下面的代碼來定義自定義 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);
}
}
我想在不同的模塊中使用這個 InterceptorConfig。 我可以打包並使用它還是需要在每個模塊中定義它?
我想對於“其他模塊”,您是在問是否可以使該代碼也可用於其他 Spring Boot 應用程序?
如果是這種情況 - 那么:是的,您可以將其打包在 jar 中,並將其作為依賴項添加到所有其他模塊中。 但是,我將在下面發布執行此操作的方法 - 只是為了警告您 - 如果它只是用於那個簡單的類,那么解決方案將不值得。
簡而言之,您需要做的是創建自己的外部工件(這通常通過 maven 或 gradle 完成。您為共享代碼創建一個新的 maven 項目。它需要依賴於一些基礎庫,以便您有你的@Configuration
注釋。把你的類放在那個項目中,並創建一個文件src/main/resources/META-INF/spring.factories
文件。 在那里你需要指向那個類。
然后構建該項目並將生成的 jar 上傳到包存儲庫。 完成后,您可以將其作為依賴項添加到您的項目中。 在啟動時,Spring boot 會找到spring.factories
文件並自動包含在其初始化中提到的類。
另請注意,這只是一個高級解釋,您將需要更多詳細信息。 Spring 有關於這個用例的很好的文檔,他們也有一個演示項目來展示這個擴展機制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.