Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

java - Reading all variables from application properties using single class

I have a springboot application with below 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:

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

}

Everthing works fine. Now I want to add 2 more variables in my application.properties file:

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). How can I read these values in my EnvConfig class?

Thanks in advance!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...