在我们的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。)
In our Spring Boot application we use application.properties, but there's a requirement from the Ops team to use XML based properties file. The format is simple. If apllication.properties looks like:
com.mail.host=mail_host db.connection.port=1521the corresponding xml should be:
<XML> <com> <mail> <host> mail_host </host> </mail> </com> <db> <connection> <port> 1521 </port> </connection> </db> </XML>We implemented that, but Spring Boot is still looking for the application.properties in order to get its specific properties. This is somewhat inconvenient. We want to have all the properties in one place, i.e. - the XML file.
What's the best way of overriding the default behavior of Spring Boot, to make it look for the properties in the XML file? (Of course, it will need some custom code, because Spring Boot understands simple property format (like key=value) and the YAML format, but no 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}")将在它将注释的任何实例变量上设置相应的值。
The problem is not to write our own XML parser. We already have that. The question is how to make Spring Boot read the specific properties from the XML file, because SB tries to read them automatically from the application.properties when the app starts and we can't make it use our custom XML parser.
Appeared to be easier than I thought. When the app starts, our code invokes a static initializer method that reads the props from the XML file using our custom parser. It sets the Spring Boot specific properties as system ones, by calling:
System.setProperty(...)Later on, the Spring Boot is able to get these prop values, just as if they are given in the application.properties.
更多推荐
发布评论