功能 - 切换Spring组件

时间:2016-08-24 14:02:29

标签: java spring spring-boot featuretoggle

我有一个Spring Boot应用程序,包含很多@ Component,@ Controller,@ RestartController注释组件。有大约20种不同的功能我想分开切换。重要的是,可以在不重建项目的情况下切换功能(重启就可以了)。我认为Spring配置会很好。

我可以像这样对配置(yml)进行成像:

myApplication:
  features:
    feature1: true
    feature2: false
    featureX: ...

主要问题是我不想在所有地方使用if-blocks。我宁愿完全禁用组件。例如,甚至应该加载@RestController,它不应该注册它的pathes。我目前正在寻找类似的东西:

@Component
@EnabledIf("myApplication.features.feature1")  // <- something like this
public class Feature1{
   // ...
}

有这样的功能吗?有没有一种简单的方法可以自己实现它?或者是否有另一种功能切换的最佳实践?

Btw:Spring Boot版本:1.3.4

4 个答案:

答案 0 :(得分:7)

您可以使用@ConditionalOnProperty注释:

@Component
@ConditionalOnProperty(prefix = "myApplication.features", name = "feature1")
public class Feature1{
   // ...
}

答案 1 :(得分:6)

有条件启用bean - 禁用时为null

@Component
@ConditionalOnProperty(prefix = "myApplication.features", name = "feature1", havingValue="true")
public class Feature1 {
    //...
}

@Autowired(required=false)
private Feature1 feature1;

如果条件bean是一个控制器,那么你不需要自动装配它,因为通常不会注入控制器。如果注入了条件bean,那么在未启用条件bean时,您将获得No qualifying bean of type [xxx.Feature1],这就是您需要使用required=false自动装配它的原因。然后它将保持null

有条件启用&amp;残疾豆

如果Feature1 bean注入其他组件,您可以使用required=false注入它,或者定义要在禁用该功能时返回的bean:

@Component
@ConditionalOnProperty(prefix = "myApplication.features", name = "feature1", havingValue="true")
public class EnabledFeature1 implements Feature1{
    //...
}

@Component
@ConditionalOnProperty(prefix = "myApplication.features", name = "feature1", havingValue="false")
public class DisabledFeature1 implements Feature1{
    //...
}

@Autowired
private Feature1 feature1;

有条件启用&amp;禁用的bean - Spring Config

@Configuration
public class Feature1Configuration{
    @Bean
    @ConditionalOnProperty(prefix = "myApplication.features", name = "feature1", havingValue="true")
    public Feature1 enabledFeature1(){
        return new EnabledFeature1();
    }

    @Bean
    @ConditionalOnProperty(prefix = "myApplication.features", name = "feature1", havingValue="false")
    public Feature1 disabledFeature1(){
        return new DisabledFeature1();
    }
}

@Autowired
private Feature1 feature1;

Spring个人资料

另一个选择是通过弹簧配置文件激活bean:@Profile("feature1")。但是,所有已启用的功能都必须列在单个属性spring.profiles.active=feature1, feature2...中,因此我认为这不是您想要的。

答案 2 :(得分:1)

尝试查看ConditionalOnExpression

也许这应该有用

@Component
@ConditionalOnExpression("${myApplication.controller.feature1:false}")  // <- something like this
public class Feature1{
   // ...
}

答案 3 :(得分:1)

FF4J是实现Feature Toggle模式的框架。它提出了spring-boot starter并允许在运行时通过专用的Web控制台启用或禁用spring组件。通过using AOP,它允许根据特征状态动态注入正确的bean。它不会在spring上下文中添加或删除bean。