以编程方式永久重写application.properties

nszi6y05  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(195)

我想开发一个api,使非程序员能够设置电子邮件属性,如端口或主机。我发现我可以使用spring boot注解@configurationproperties在类中加载属性。

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

    private Long port;
    private String host;

}

我可以使用getport检索属性,并使用setport进行设置。
但是,使用此方法时,application.properties文件中的实际值´当我使用setport或sethost时不会改变。因此,当我重新启动应用程序时,更改会丢失。有没有办法实际更改application.properties文件中的值,或者需要一个数据库,以便在应用程序启动时从中加载属性?

4xy9mtcn

4xy9mtcn1#

您可以外部化配置文件(查看spring文档)。
为此,请在pom.xml中添加以下依赖项:
Maven:

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

然后在git服务器上创建git存储库,并将以下内容添加到application.properties中:

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

并将@enableconfigserver注解添加到springbootapplication类中。最后,通过将以下内容添加到application.properties,将应用程序链接到配置服务器:

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

更多细节,请查看这个不错的教程。

相关问题