Como usar o resultado SpEL como chave @Value

Nov 20 2020

No meu aplicativo springboot, quero usar @Value para ler alguns configure, mas esse configure é usado em muitos outros métodos, então quero definir a chave do configure como uma constante. Este é o código:

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

Neste Código variável "SUPPORT_MANAGER_PLANE_INSTANCES" usados por @Valuee processConfigureChangemétodo, se necessário modificar o valor dessa variável Eu preciso modificar todos se referem a esta variável, assim que eu quero definir uma variável constante CONFIGURE_KEY @Valuee processConfigureChangeuso do método desta variável.

Respostas

1 TongChen Nov 20 2020 at 14:16

Ajuda de Thans @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);
    }
}