Java 更可读的Spring@Value参数

Java 更可读的Spring@Value参数,java,configuration,spring-4,Java,Configuration,Spring 4,我知道这个话题可能会被认为是离题的或基于惯例/观点的,但我还没有找到任何其他地方可以解决我的问题 我正在编写和Spring应用程序,用Java完全配置了注释。我正在加载带有@PropertySource注释的属性文件: @Configuration @ComponentScan("myapp.app") @PropertySource("app.properties") public class ApplicationConfig { @Bean public static Pr

我知道这个话题可能会被认为是离题的或基于惯例/观点的,但我还没有找到任何其他地方可以解决我的问题

我正在编写和Spring应用程序,用Java完全配置了注释。我正在加载带有@PropertySource注释的属性文件:

@Configuration
@ComponentScan("myapp.app")
@PropertySource("app.properties")
public class ApplicationConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}
假设我有以下内容的app.properties文件:

property1=someProperty1Value
property2=someProperty2Value
我正在使用以下代码加载此值:

@Service
public class MyServiceImpl implements MyService {
    @Value("${property1}")
    private String property1Value;

    @Value("${property2}")
    private String property2Value;

    @Override
    public void doStuff() {
        System.out.println(property1Value);
        System.out.println(property2Value);
    }
}
这很好用。另一方面,我发现很难维护—如果有些人认为“property1”不是属性的最佳名称,并希望对其进行重命名,则需要找到所有字符串“${property1}”,并对其进行重命名。我认为我可以将其提取到常量类:

public final class Properties {
    public static final String PROPERTY_1 = "${property1}";
    public static final String PROPERTY_2 = "${property2}";

    private Properties() {  
    }
}
这需要将现有绑定重构为新的常量值:

@Value(Properties.PROPERTY_1)
private String property1Value;
看起来不错,但我不喜欢Properties类中的混乱,我认为最好是不带手镯的常量值:

public static final String PROPERTY_1 = "property1";
这将导致MyServiceImpl类中的另一次重构:

@Value("${" + Properties.PROPERTY_1 + "}")
private String property1Value;
但是,孩子,那真的很难看。我考虑将常量值提取到枚举:

public enum Properties {
    PROPERTY_1("property1"), 
    PROPERTY_2("property2");

    private final String key;

    private Properties(String key) {
        this.key = key;
    }
    public String getKey() {
        return key;
    }
    public String getSpringKey() {
        return "${" + getKey() + "}";
    }
}
像这样使用它

@Value(Properties.PROPERTY_1.getSpringKey())
private String property1Value;
但IDE提醒我,注释值必须是常量

创建此枚举后,我认为我可能想得太多了,应该尽可能保持简单。目前,我返回到解决方案,其中常量的格式为

public static final String PROPERTY_1 = "${property1}";
最后,我想请您提供另一个好看的解决方案,或者提供一些参考链接,让我可以阅读一些常见的解决方案