求Spring Modulith中ApplicationModuleDetectionStrategy接口实现示例
自定义Spring Modulith模块检测策略:ApplicationModuleDetectionStrategy实现示例
Spring Modulith的ApplicationModuleDetectionStrategy接口用于自定义模块的检测逻辑,可替代默认的包结构检测规则。下面是两个实用的实现示例:
示例1:基于指定包前缀的模块检测
此实现会将所有以com.myapp.module.开头的子包识别为独立模块:
import org.springframework.modulith.core.ApplicationModule; import org.springframework.modulith.core.ApplicationModuleDetectionStrategy; import org.springframework.modulith.core.NamedInterface; import org.springframework.modulith.core.Types; import java.util.Set; import java.util.stream.Collectors; public class PrefixBasedModuleDetectionStrategy implements ApplicationModuleDetectionStrategy { private static final String MODULE_PREFIX = "com.myapp.module."; @Override public Set<ApplicationModule> detect(Types types) { // 过滤符合前缀的包,每个包对应一个模块 return types.getTypesByPackage() .keySet() .stream() .filter(pkg -> pkg.startsWith(MODULE_PREFIX)) .map(pkg -> ApplicationModule.of(pkg, types)) .collect(Collectors.toSet()); } @Override public Set<NamedInterface> detectNamedInterfaces(ApplicationModule module) { // 将模块下的api子包标记为公开接口 return module.getPackage() .getSubpackages("api") .stream() .map(subpkg -> NamedInterface.of("api", subpkg)) .collect(Collectors.toSet()); } }
示例2:基于类注解的模块检测
此实现会将包含自定义@MyModule注解的类所在包识别为模块:
import org.springframework.modulith.core.ApplicationModule; import org.springframework.modulith.core.ApplicationModuleDetectionStrategy; import org.springframework.modulith.core.NamedInterface; import org.springframework.modulith.core.Types; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Set; import java.util.stream.Collectors; // 自定义模块标记注解 @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface MyModule {} // 检测策略实现 public class AnnotationBasedModuleDetectionStrategy implements ApplicationModuleDetectionStrategy { @Override public Set<ApplicationModule> detect(Types types) { // 提取所有标注@MyModule的类所在包,去重后生成模块 return types.getTypesAnnotatedWith(MyModule.class) .stream() .map(type -> type.getPackage()) .distinct() .map(pkg -> ApplicationModule.of(pkg, types)) .collect(Collectors.toSet()); } @Override public Set<NamedInterface> detectNamedInterfaces(ApplicationModule module) { // 将模块根包作为默认公开接口 return Set.of(NamedInterface.of("public", module.getPackage())); } }
启用自定义策略
在Spring Boot应用中,只需将自定义策略类注册为Spring Bean即可生效:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ModulithConfig { @Bean public ApplicationModuleDetectionStrategy customModuleDetectionStrategy() { return new PrefixBasedModuleDetectionStrategy(); // 可替换为AnnotationBasedModuleDetectionStrategy } }
内容的提问来源于stack exchange,提问作者Diferdin
相关产品推荐
相关产品推荐

