Spring 的@Profile on methods 是一个好习惯吗

Is Spring's @Profile on methods a good practice

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

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

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

我的过滤器配置 class 如下:

@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;
    }
}

我的问题是:

谢谢。

Is it a good practice to add @Profile on method?

这是解决此问题的 spring 方法 - 因此它符合 spring 生态系统

Is there a way to force the compiler to exclude classes, methods, etc. annotated with a diferent profiles than the one set as current? (I don't want my production jar/war populated with unnecessary code!)

您必须调整构建以排除 类 - 另一种方法是使用 ID 配置 bean,并根据环境使用 ID 和配置。类似于 to

的方法

根据我的经验,配置文件更容易

Does spring boot provide a clearer way to organize profiles?

据我所知,除了上述link中的方法

我认为最好在不同的包中针对不同的环境进行配置。你不想混合你的配置。 结构可能如下所示:

config
    - Config1.java
    - Config2.java
    dev
        - WebConfig.java
        - DataConfig.java
    prod
        - WebConfig.java
        - DataConfig.java

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

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

底线:为 properties 定义配置文件,而不是为 @Configuration@Bean 定义配置文件。

如果你真的想排除生产代码的测试内容,请查看 spring-boot-devtools 的文档,如果你使用 Maven,你可以将所有测试 classes/resources 放在一个单独的模块中,并将其标记为 <optional>true</optional> 或为其定义 maven 配置文件。请注意,同时拥有 maven 配置文件和 spring 引导配置文件可能会造成混淆!