我试图使用Spring Boot配置属性。我将项目打包为jar文件,需要能够根据需要更改属性(在jar外部)中配置的值,并且属性文件的位置应相对于jar文件。以下示例代码演示了如何使用Java库做到这一点:
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提供的Environment
类来获取属性。不幸的是,在使用System.getProperty("user.dir")
注释时,我无法使用@PropertySource
来设置路径值。我需要将属性文件的路径设置为相对于应用程序,而不是在系统环境变量中进行配置。有没有一种方法可以解决该问题并获取用户目录?
我尝试在配置类中使用PropertySourcesPlaceholderConfigurer
。看来在这种情况下,我将无法使用Environment
类来获取属性。
答案 0 :(得分:0)
因此,解决方案基于以下事实:我们可以通过在清单文件中指定项目来扩展类路径。所以我们需要
1)将属性文件保留在/ src / main / resources中。
2)将其从最终的jar中排除
<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>
3)在罐子外面建立一个文件夹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>
5)指定清单文件,该文件指向conf文件夹(步骤1的一部分-在那里)
<archive>
<manifest>
<mainClass>com.blabla.daemon.MainListener</mainClass>
<classpathPrefix>lib/</classpathPrefix>
<addClasspath>true</addClasspath>
</manifest>
<manifestEntries>
<Class-Path>conf/</Class-Path>
</manifestEntries>
</archive>