Comment utiliser le résultat SpEL comme clé @Value

Nov 20 2020

Dans mon application springboot, je veux utiliser @Value pour lire certains configure, mais cette configuration est utilisée dans de nombreuses autres méthodes, je veux donc définir la clé de configure comme une constante.

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

Dans cette variable de code "SUPPORT_MANAGER_PLANE_INSTANCES" utilisée par @Valueet processConfigureChangeméthode, si besoin de modifier la valeur de cette variable, je dois modifier toutes les références à cette variable, donc je veux définir une variable constante CONFIGURE_KEY @Valueet la processConfigureChangeméthode utilise cette variable.

Réponses

1 TongChen Nov 20 2020 at 14:16

L'aide 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);
    }
}