【问题标题】:How use SpEL result as @Value key如何使用 SpEL 结果作为 @Value 键
【发布时间】:2020-11-20 03:03:08
【问题描述】:

在我的 springboot 应用程序中,我想使用 @Value 来读取一些配置,但是这个配置用于许多其他方法,所以我想将配置的键定义为一个常量。这是代码:

@Component
public class InstanceConfig {

    private static final String CONFIGURE_KEY = "SUPPORT_MANAGER_PLANE_INSTANCES";

    @Value("${SUPPORT_MANAGER_PLANE_INSTANCES}")
    private String supportManageInstances;
    
    @ApolloConfigChangeListener(value = ConfigConsts.NAMESPACE_APPLICATION)
    public void processConfigureChange(ConfigChangeEvent event) {
        log.info("configure changed do somthing");
        ConfigChange configChange = event.getChange("SUPPORT_MANAGER_PLANE_INSTANCES");
    }
}

@ValueprocessConfigureChange方法使用的这个代码变量“SUPPORT_MANAGER_PLANE_INSTANCES”中,如果需要修改这个变量的值我需要修改所有引用这个变量,所以我想定义一个常量变量CONFIGURE_KEY@ValueprocessConfigureChange 方法使用这个变量。

【问题讨论】:

  • 也许这会有所帮助:stackoverflow.com/a/30597973/11640072
  • 用于许多其他方法 请提供更多详细信息。根据您的案例的具体情况,可能有一种现有的模式可供使用。
  • 考虑包装在 @Configuraton 类中,以便将值注入单个类中。然后在需要了解namespace的其他类中注入配置类。 config 类提供了一个简单的 getter 方法。
  • 如果我们从public String getConfigureKey()这样的函数中获取CONFIGURE_KEY的值,我们应该如何定义@Value("???")?

标签: java spring spring-boot spring-el


【解决方案1】:

感谢@hirarqi 的帮助

@Component
public class InstanceConfig {

    private static final String CONFIGURE_KEY = "SUPPORT_MANAGER_PLANE_INSTANCES";

    @Value("${" + CONFIGURE_KEY + "}")
    private String supportManageInstances;
    
    @ApolloConfigChangeListener(value = ConfigConsts.NAMESPACE_APPLICATION)
    public void processConfigureChange(ConfigChangeEvent event) {
        log.info("configure changed do somthing");
        ConfigChange configChange = event.getChange(CONFIGURE_KEY);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    相关资源
    最近更新 更多