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
109 views
in Technique[技术] by (71.8m points)

java - Permanently overriding application.properties programatically

I would like to develop an API which enables a non-programmer to set e-mail properties like the port or a the host. I discovered that I can load properties in a class using the Spring Boot annotation @ConfigurationProperties.

@Configuration
@ConfigurationProperties(prefix = "company.mail")
@Data
public class ConfigProperties {

    private Long port;
    private String host;

}

I can retrieve the properties using e.g. getPort and set them using setPort.

However, using this method the actual values in the application.properties file don′t change when I use setPort or setHost. Consequently the changes get lost when I restart the application. Is there a way to actually change the values in the application.properties file or do I need a database from where I can load the properties when the application starts?

question from:https://stackoverflow.com/questions/66066751/permanently-overriding-application-properties-programatically

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

1 Reply

0 votes
by (71.8m points)

You can externalize your config files (check spring documentation).

In order to do so add the following dependency in your pom.xml:

Maven:

<dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

then on your git server create a git repository and add the following into your application.properties:

spring.cloud.config.server.git.uri=http://{yourGitRepoUrl}.git 

And add @EnableConfigServer annotation to your SpringBootApplication class. and finally link your app to your config server by adding the following to application.properties:

spring.cloud.config.uri=http://localhost:8080  #whatever your port is

For more detail check this nice Tutorial.


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

...