3

In my springboot application i want use @Value to read some configure,but this configure's used in many other methods,so i want define configure's key as a constant.This is the code:

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

In this code variable "SUPPORT_MANAGER_PLANE_INSTANCES" used by @Value and processConfigureChange method,if need to modify this variable's value i need modify all refer this variable,so i want define one constant variable CONFIGURE_KEY @Value and processConfigureChange method use this variable.

TongChen
  • 1,414
  • 1
  • 11
  • 21
  • 1
    maybe this can help : https://stackoverflow.com/a/30597973/11640072 – hirarqi Nov 20 '20 at 03:14
  • *used in many other methods* Please provide more details. There's likely an existing pattern to use depending on the specifics of your case. – chrylis -cautiouslyoptimistic- Nov 20 '20 at 04:01
  • Consider wrapping in an @Configuraton class so the value is injected within a single class. Then inject the configuration class in the other classes which need to know about `namespace`. The config class provides a simple getter method. – Andrew S Nov 20 '20 at 04:37
  • if we get CONFIGURE_KEY’s value from a function like public String getConfigureKey() how should we define @Value("???")? – TongChen Nov 20 '20 at 07:18

1 Answers1

1

Thans @hirarqi's help

@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);
    }
}
TongChen
  • 1,414
  • 1
  • 11
  • 21