Java 主类在运行时重写属性文件

标签 java spring maven properties jar

我正在使用 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/

相关文章:

Java - @ResponseBody 字符串 - 错误 200

java - Hibernate二级缓存并不是在所有情况下都使用

java - servlet.PageNotFound : No mapping found for HTTP request with URI in DispatcherServlet

java - Citrus 框架 - 无法成功构建示例

java httpunit.http异常 :Error on HTTP request: 405 Method Not Allowed [url]

java - 如何将算法缩减为更小的部分以便我可以扩展它?

java - 使用什么语言来执行 mcmc 算法?

java - Spring @ControllerAdvice 异常处理程序返回 404 错误而不是 View

java - 无法使用 MAVEN 进行构建,出现错误 - 无法执行目标 org.apache.maven.plugins :maven-compiler-plugin:2. 3.2:compile

java - 将 sourceforge 依赖项添加到 Gradle 项目