Spring 在方法上的 @Profile 是一个好的实践吗

Luc*_*.de 4 java spring maven spring-profiles spring-boot

我有一个公开休息服务的 Spring Boot Web 应用程序。

我问自己如何正确管理过滤器上的配置文件。实际上,我的应用程序有 2 个配置文件:dev 和 prod(你猜它代表什么......)

在产品模式下,我比开发模式下有更多的过滤器需要激活。

我的过滤器配置类如下:

@Configuration
public class FiltersConfig {

    @Bean
    public FilterRegistrationBean filterRegistrationBean(CompositeFilter compositeFilter){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.setFilter(compositeFilter);
        return filterRegistrationBean;
    }

    @Bean
    @Profile("dev")
    public CompositeFilter devCompositeFilter(){
        CompositeFilter compositeFilter = new CompositeFilter();
        List<Filter> filtersList = new ArrayList<>();
        //filtersList.add(filter1());
        compositeFilter.setFilters(filtersList);
        return compositeFilter;
    }


    @Bean
    @Profile("prod")
    public CompositeFilter prodCompositeFilter(){
        CompositeFilter compositeFilter = new CompositeFilter();
        List<Filter> filtersList = new ArrayList<>();
        //filtersList.add(filter1());
        compositeFilter.setFilters(filtersList);
        return compositeFilter;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  • 在方法上添加 @Profile 是一个好习惯吗?
  • 有没有一种方法可以强制编译器排除使用与当前设置不同的配置文件注释的类、方法等?(我不希望我的生产 jar/war 中填充不必要的代码!)
  • Spring Boot 是否提供了更清晰的方式来组织配置文件?

谢谢。

tan*_*an9 6

根据我自己的经验,@Profile在任何 java 代码中使用都不是一个好主意。这就是为什么我认为你必须避免在代码中使用它:

  1. 您始终可以定义属性,例如my.feature-for-the-profile.enabled使用配置文件来实现相同的目标。
  2. 配置文件有时会有所不同,保留每一个更改的配置,因为属性可以让您更好地控制任何地方的一切。
  3. Spring Boot 具有明确定义的特定于配置文件的外部化属性支持(如 application- prod.yml)。在代码库中包含配置文件会使事情变得更加复杂,有时甚至会产生误导。
  4. 您可以使用属性来修改或覆盖,这比更新和重新编译代码更容易。
  5. ProfileCondition(作为 上的元注释@Profile)不是 a SpringBootCondition,您不能使用它/autoconfig来确定它是否已激活。

底线:为 定义配置文件properties,而不是为@Configurations 或@Beans 定义配置文件。

如果你真的想在你的生产代码中排除测试内容,请查看spring-boot-devtools的文档,如果你使用 Maven,你可以将所有测试类/资源放在一个单独的模块中,并将其标记为<optional>true</optional>或定义Maven 配置文件。请注意,同时拥有 Maven 配置文件和 Spring Boot 配置文件可能会令人困惑!