我正在使用 Apache Maven 和 Spring。在 src/main/resources 文件夹中,我有一个属性文件。这些属性值可以有不同的值。
我正在使用 PropertyPlaceholderConfigurer。
@Configuration
public class ResourceConfig {
@Bean
public PropertyPlaceholderConfigurer properties( ) {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setIgnoreResourceNotFound(true);
ppc.setLocations(new ClassPathResource[] {new ClassPathResource("propertiesFile")});
return ppc;
}
}
我在运行时替换这些值:
@Configuration
public class DataSourceConfig {
@Value("${jdbc.url}")
private String jdbcUrlDefault;
}
这只是一个示例。我有一个主要方法:
public static void main(String[] args) {
// accept a properties file and replace those values defined in DataSourceConfig class
}
当 Apache Maven 构建应用程序时,属性文件将位于类路径中。属性文件在单元测试期间使用。我想知道如何在主程序启动用于生产之前用新的属性文件替换属性。
我看过一些 Properties.load() 的示例,但我不想这样做。我想通过被替换的主程序接受属性文件,因此Spring端启动PropertyPlaceholderConfigurer。
如何实现这一目标?
最佳答案
您可以将测试属性文件放置在src/test/resources/
中。在测试类中,它将使用此位置的属性文件。
放置在上面位置的属性文件不会包含在最终构建的类路径中。
使用src/main/resources
将您想要的资源文件放置在主程序中
关于Java 主类在运行时重写属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25661420/