繁体   English   中英

如何在Spring Boot应用程序中排除给定运行时配置文件中的包

[英]How to exclude package in given runtime profile in Spring Boot application

在我的应用程序中,我有两个概要文件devprod ,我可以使用org.springframework.context.annotation.Profile注释排除bean:

package com.example.prod;

@Service
@Profile("prod")
public class MyService implements MyBaseService {}

问题是,我有几个以这种方式注释的bean,它们都在同一个包com.example.prod dev配置文件( com.example.dev软件包)也存在类似的结构,将来我可能还会有一些其他配置文件。 是否有可能一次排除整个包装? 我尝试使用org.springframework.context.annotation.ComponentScan ,但是我无法根据实际配置文件添加排除过滤器,我想知道是否有简单的方法可以解决我的问题。

您可以实现一个自定义TypeFilter以基于活动配置文件为某些软件包禁用ComponentScan 一个启动示例是:

(1)实施过滤器。 出于演示目的,我对如果活动配置文件是dev了硬编码,它将排除由devExcludePackage属性配置的软件包。 对于prod配置文件,它将排除由prodExcludePackage配置的prodExcludePackage

public class ExcludePackageTypeFilter implements TypeFilter , EnvironmentAware  {

    private Environment env;

    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
            throws IOException {

        boolean match = false;
        for (String activeProfile : env.getActiveProfiles()) {
            if (activeProfile.equals("dev")) {
                match = isClassInPackage(metadataReader.getClassMetadata(), env.getProperty("devExcludePackage"));
            } else if (activeProfile.equals("prod")) {
                match = isClassInPackage(metadataReader.getClassMetadata(), env.getProperty("prodExcludePackage"));
            }
        }
        return match;
    }

    private boolean isClassInPackage(ClassMetadata classMetadata, String pacakage) {
        return classMetadata.getClassName().startsWith(pacakage);
    }


    @Override
    public void setEnvironment(Environment environment) {
        this.env = environment;
    }
} 

(2)配置application.properties以定义要针对不同概要文件排除的软件包。

devExcludePackage  = com.example.prod
prodExcludePackage = com.example.dev

(3)将此过滤器应用于@ComponentScan

@SpringBootApplication
@ComponentScan(excludeFilters = @ComponentScan.Filter(
                type = FilterType.CUSTOM, classes = { ExcludePackageTypeFilter.class }))
public class Application {


}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM