在我们的 Spring Boot 应用程序中,我们使用 application.properties,但 Ops 团队要求使用基于 XML 的属性文件。格式很简单。如果 apllication.properties 看起来像:
com.mail.host=mail_host
db.connection.port=1521
对应的xml应该是:
<XML>
<com>
<mail>
<host>
mail_host
</host>
</mail>
</com>
<db>
<connection>
<port>
1521
</port>
</connection>
</db>
</XML>
我们实现了它,但 Spring Boot 仍在寻找 application.properties 以获得其特定属性。这有点不方便。我们希望将所有属性放在一个地方,即 - XML 文件。
覆盖 Spring Boot 的默认行为以使其在 XML 文件中查找属性的最佳方法是什么? (当然,它需要一些自定义代码,因为 Spring Boot 理解简单的属性格式(如 key=value)和 YAML 格式,但不理解 XML。)
最佳答案
Spring Boot 不仅可以从扩展名为 .properties 和 .yaml 的文件中读取属性,还可以从 .xml 中读取属性。而不是 application.properties 只是以下列格式在您的资源文件夹中提供 application.xml:-
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Application properties in XML format</comment>
<entry key="com.mail.host">mail_host</entry>
<entry key="db.connection.port">1521</entry>
</properties>
在您的类文件中,您可以简单地设置值,就像我们对任何属性或 yaml 文件所做的那样,即 @Value("${com.mail.host}")
将设置相应的值它将注释到的任何实例变量。
关于xml - 我可以在 Spring Boot 应用程序中使用 xml 属性文件而不是 application.properties 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33003903/