使用application.properties在Spring中配置枚举 [英] Configuring an enum in Spring using application.properties

查看:1648
本文介绍了使用application.properties在Spring中配置枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下枚举:

public enum MyEnum {
    NAME("Name", "Good", 100),
    FAME("Fame", "Bad", 200);

    private String lowerCase;
    private String atitude;
    private long someNumber;

    MyEnum(String lowerCase, String atitude, long someNumber) {
        this.lowerCase = lowerCase;
        this.atitude = atitude;
        this.someNumber = someNumber;
    }
}

我想为两个实例设置不同的someNumber变量使用application.properties文件的枚举。
这是否可能,如果不能,是否应该使用抽象类/接口将其分为两个类?

I want to setup the someNumber variable different for both instances of the enum using application.properties file. Is this possible and if not, should i split it into two classes using an abstract class/interface for the abstraction?

推荐答案

您不能/不应该在Java中更改枚举的值。尝试改用类:

You can't/shouldn't change values of a enum in Java. Try using a class instead:

public class MyCustomProperty { 
    // can't change this in application.properties
    private final String lowerCase;
    // can change this in application.properties
    private String atitude;
    private long someNumber;

    public MyCustomProperty (String lowerCase, String atitude, long someNumber) {
        this.lowerCase = lowerCase;
        this.atitude = atitude;
        this.someNumber = someNumber;
    }
    // getter and Setters
}

比创建自定义配置属性

@ConfigurationProperties(prefix="my.config")
public class MyConfigConfigurationProperties {
    MyCustomProperty name = new MyCustomProperty("name", "good", 100);
    MyCustomProperty fame = new MyCustomProperty("fame", "good", 100);

    // getter and Setters

    // You can also embed the class MyCustomProperty here as a static class. 
    // For details/example look at the linked SpringBoot Documentation
}

现在,您可以在页面中更改 my.config.name.someNumber my.config.fame.someNumber 的值。 application.properties文件。如果要禁止更改小写字母/高度,请将其定为最终值。

Now you can change the values of my.config.name.someNumber and my.config.fame.someNumber in the application.properties file. If you want to disallow the change of lowercase/atitude make them final.

在使用它之前,必须先注释一个 @Configuration @EnableConfigurationProperties(MyConfigConfigurationProperties.class) 的code>类。还要添加 org.springframework.boot:spring-boot-configuration-processor 作为可选依赖项以获得更好的IDE支持。

Before you can use it you have to annotate a @Configuration class with @EnableConfigurationProperties(MyConfigConfigurationProperties.class). Also add the org.springframework.boot:spring-boot-configuration-processor as an optional dependency for a better IDE Support.

如果要访问值:

@Autowired
MyConfigConfigurationProperties config;
...
config.getName().getSumeNumber();

这篇关于使用application.properties在Spring中配置枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆