在*.properties文件中 使用pom.xml中<properties>元素

本文介绍了如何在*.properties文件中使用Maven工程的pom.xml文件中定义的<properties>元素。通过配置pom.xml的<build>部分,可以将预设置变量引入到*.properties文件,并进行测试,最终观察输出结果。

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即可

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值