Cómo usar el resultado de SpEL como clave @Value

Nov 20 2020

En mi aplicación springboot quiero usar @Value para leer alguna configuración, pero esta configuración se usa en muchos otros métodos, así que quiero definir la clave de configure como una constante. Este es el 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");
    }
}

En este código variable "SUPPORT_MANAGER_PLANE_INSTANCES" utilizados por @Valuey processConfigureChangemétodo, si necesidad de modificar el valor de esta variable que necesito modificar todos se refieren a esta variable, por lo que quiero definir una variable constante CONFIGURE_KEY @Valuey processConfigureChangeel uso del método de esta variable.

Respuestas

1 TongChen Nov 20 2020 at 14:16

La ayuda 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);
    }
}