简体   繁体   English

使用单个 class 从应用程序属性中读取所有变量

[英]Reading all variables from application properties using single class

I have a Spring Boot application with the below application.properties:我有一个 Spring 引导应用程序,具有以下 application.properties:

message=default1
security.url=defaultSecurityURL.com
security.authMethod=defaultAuth
security.roles=USER,ADMIN,PARTNER  
message_temp=dummyvaluehere 

Now, I have a Java class that reads all these variables from the application.properties:现在,我有一个从 application.properties 读取所有这些变量的 Java class:

@ConfigurationProperties 
@ConstructorBinding
public final class EnvConfig {

    private final String message;
    private final Security security; //there is a Security class defined seperately
    private final String messageTemp;
    
    public EnvConfig(String message, Security security, String messageTemp) {
        super();
        this.message = message;
        this.security = new Security(security.getUrl(), security.getAuthMethod(), security.getRoles()); //this is done for immutability
        this.messageTemp = messageTemp;
    }

    public String getMessage() {
        return message;
    }
    public Security getSecurity() {
        return security;
    }
    public String getMessageTemp() {
        return messageTemp;
    }

    @Override
    public String toString() {
        return "EnvConfig [message=" + message + ", security=" + security + ", messageTemp="
                + messageTemp + "]";
    }
}

Everything works fine.一切正常。 Now I want to add 2 more variables to my application.properties file:现在我想在我的 application.properties 文件中再添加 2 个变量:

message.default.app.deploy.strategy=bg
message.default.app.deploy.retries=3

But I don't want to read these variables by declaring a new class (like I created a Security class above).但是我不想通过声明一个新的 class 来读取这些变量(就像我在上面创建了一个安全 class 一样)。 How can I read these values in my EnvConfig class?如何在我的 EnvConfig class 中读取这些值?

Look in my answer of this SO question which offers a generic way to access all variables of the spring environment (by its string key).查看我对这个 SO question的回答,它提供了一种访问 spring 环境的所有变量的通用方法(通过其字符串键)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM