我正在尝试制作两个maven配置文件,我认为我做错了。阅读Maven网站并完成建议,但仍然没有将值从Pom.xml传递到属性文件 我的Pom.xml:
<name>maven-create-profiles</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<resource.dir>src/main/resources</resource.dir>
</properties>
<profiles>
<profile>
<id>dev</id>
<properties>
<environment>dev</environment>
<db.username>myDevUser</db.username>
<db.password>secretDevPasswd</db.password>
<db.url>jdbc:mysql://localhost/myDb</db.url>
<db.dialect>org.hibernate.dialect.MySQL5Dialect</db.dialect>
<db.driver>com.mysql.jdbc.Driver</db.driver>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
<property>
<name>environment</name>
<value>dev</value>
</property>
</activation>
</profile>
<profile>
<id>prod</id>
<properties>
<environment>prod</environment>
<db.username>myProdUser</db.username>
<db.password>secretProdPasswd</db.password>
<db.url>jdbc:mysql://production-database/myDb</db.url>
<db.dialect>org.hibernate.dialect.MySQL5Dialect</db.dialect>
<db.driver>com.mysql.jdbc.Driver</db.driver>
</properties>
<activation>
<property>
<name>environment</name>
<value>prod</value>
</property>
</activation>
</profile>
</profiles>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
我的属性文件:
db.username=${db.username}
db.password=${db.password}
db.url=${db.url}
db.dialect=${db.dialect}
db.driver=${db.driver}
我的java课程:
public class MyTest {
static String userName;
static String myPassword;
static String myAccount;
@BeforeClass
public void setUp() throws IOException {
Properties properties = new Properties();
properties.load(new FileInputStream("src/main/resources/db.properties"));
userName = properties.getProperty("db.username");
myPassword = properties.getProperty("db.password");
myAccount = properties.getProperty("db.url");
}
@Test
public void myTest() {
System.out.println(userName);
System.out.println(myPassword);
System.out.println(myAccount);
}
}
执行后我得到了结果:
${db.username}
${db.password}
${db.url}
但我实际上想要获得我在maven配置文件中传递的内容(这是制作这些配置文件的主要原因)。提前谢谢你们!!
答案 0 :(得分:0)
Maven不会修改您的来源,而是在将资源复制到/target
时应用过滤。但是,您不应该仅使用src/main/resources
替换target
。相反,您应该从类路径获取最终资源,例如:
properties.load(MyTest.class.getResourceAsStream("/db.properties"));
我建议首先确保使用默认值而不使用任何配置文件,然后添加配置文件。