1.创建一个Maven工程
2.配置pom.xml文件 如下
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>DubboTest</groupId> <artifactId>Dubbo</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>Dubbo Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <f>af</f> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <resources> <resource> <directory>src\main\resources</directory> <filtering>true</filtering> </resource> </resources> </build> </project>
<f>为预设置变量 若想在*.propertis或*.xml文件中使用pom.xml文件中变量 请在pom.xml文件中<build>部分
3.创建*.properties文件如下
af=${f}4.测试
public static void main(String arg[]) throws IOException {
Properties properties=new Properties();
FileInputStream file=null;
test test=new test();
ClassLoader classLoader = test.class.getClassLoader();
URL resource = test.class.getClassLoader().getResource("s.properties");
System.out.println(resource.getPath());
try{
file=new FileInputStream(resource.getPath());
}catch (Exception e){
file.close();
System.out.println("1111");
}
properties.load(file);
String af = (String) properties.get("af");
System.out.println(af);
file.close();
}5.输出结果
/F:/Dubbo/target/classes/s.properties
af
7.原因
在资源文件(*.properties)中放置pom.xml预先设置的变量, 在执行mvn package时就会自动将变量替换为真实值
例如:
1. 我们在src\main\resources\application.properties放置如下内容
version=${project.version}
2. 配置pom.xml让Maven to copy that file into your output classes and translate the resource during that copy, interpreting the property
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
3. 执行mvn package
查看生成的jar文件中的application.properties, version值已经变成了pom.xml中的version
因此我们只需使用java读取application.properties即可
本文介绍了如何在*.properties文件中使用Maven工程的pom.xml文件中定义的<properties>元素。通过配置pom.xml的<build>部分,可以将预设置变量引入到*.properties文件,并进行测试,最终观察输出结果。
703

被折叠的 条评论
为什么被折叠?



