Java 使用spring boot配置和加载多个属性
我试图使用SpringBoot配置属性。我将把项目打包为一个jar文件,需要能够根据需要更改在属性(jar外部)中配置的值,并且属性文件的位置应该相对于jar文件。以下示例代码演示了我如何使用java库实现这一点:Java 使用spring boot配置和加载多个属性,java,spring-boot,properties,environment,Java,Spring Boot,Properties,Environment,我试图使用SpringBoot配置属性。我将把项目打包为一个jar文件,需要能够根据需要更改在属性(jar外部)中配置的值,并且属性文件的位置应该相对于jar文件。以下示例代码演示了我如何使用java库实现这一点: Properties properties = new Properties(); String path = System.getProperty("user.dir")+"/config/linuxScripts.properties"; try(FileInputStream
Properties properties = new Properties();
String path = System.getProperty("user.dir")+"/config/linuxScripts.properties";
try(FileInputStream fis = new FileInputStream(path)) {
prop.load(fis);
}catch (Exception e) {
e.printStackTrace();
}
现在,我想配置位于jar文件外部的多个属性。我使用了@PropertySource
注释,并且我能够使用spring boot提供的环境
类获取属性。不幸的是,在使用@PropertySource
注释时,我无法使用System.getProperty(“user.dir”)
来设置路径值。我需要将属性文件的路径设置为相对于应用程序的路径,而不是在系统环境变量中配置的路径。有没有办法解决这个问题并获取用户目录
我已尝试在配置类中使用
propertysourcesplaceplaceconfigurer
。在这种情况下,我似乎无法使用环境
类获取属性。因此解决方案基于这样一个事实,即我们可以通过在清单文件中指定项来扩展类路径。所以我们需要
1) 将属性文件保留在/src/main/resources中
2) 从最后一个罐子中排除它
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<excludes>
<exclude>**/*.properties</exclude>
</excludes>
<archive>
<manifest>
<mainClass>com.blabla.daemon.MainListener</mainClass>
<classpathPrefix>lib/</classpathPrefix>
<addClasspath>true</addClasspath>
</manifest>
<manifestEntries>
<Class-Path>conf/</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
org.apache.maven.plugins
maven jar插件
2.4
**/*.物业
com.blabla.daemon.mainlister
解放党/
真的
形态/
3) 在jar外部创建文件夹conf
4) 使用maven从资源文件夹复制这些属性文件
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<id>copy-resources</id>
<phase>install</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/conf</outputDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
org.apache.maven.plugins
maven资源插件
2.3
复制资源
安装
复制资源
${basedir}/target/conf
src/main/resources
**/*.物业
5) 指定指向conf文件夹的清单文件(步骤1的一部分-参见此处)
com.blabla.daemon.mainlister
解放党/
真的
形态/
<archive>
<manifest>
<mainClass>com.blabla.daemon.MainListener</mainClass>
<classpathPrefix>lib/</classpathPrefix>
<addClasspath>true</addClasspath>
</manifest>
<manifestEntries>
<Class-Path>conf/</Class-Path>
</manifestEntries>
</archive>