【问题标题】:Set spring properties file location from command line从命令行设置弹簧属性文件位置
【发布时间】:2019-11-03 04:09:19
【问题描述】:

我有一个简单的 Spring 应用程序,它从属性文件中读取配置值。该文件默认配置为在类路径上(配置类上的@PropertySource("classpath:thefile.properties") 注释)。我希望能够可选地使用我可以(但不必)在程序启动时在命令行中指定的另一个属性文件。即,我最终想要运行这样的东西:

java -jar application.jar --path "some/location/thefile.properties"

现在应该使用指定文件中的值。

我已经尝试在 jar 之前和之后使用 SpringBoot 和 spring.config.location 选项:

java -jar "-Dspring.config.location=file:some/location/thefile.properties" application.jar
  • 继续使用类路径上文件中的值
java -jar application.jar "--spring.config.location=file:some/location/thefile.properties"
  • 抱怨无法识别的选项

我的主课是这样的:

@SpringBootApplication
public class MainClass {
    public static void main(String[] args) {
        SpringApplication.run(MainClass.class, args);
        // Application code triggered here...
    }
}

我不需要使用 SpringBoot,我只是想以某种方式设置属性文件位置。任何想法?这可能吗?

【问题讨论】:

  • 试试java -jar -Dspring.config.location=some/location/thefile.properties application.jar,这应该可以正常工作
  • 不,这也行不通。它仍然使用来自类路径的文件中的值。
  • java -jar my-awesome-java-prog.jar --spring.config.location=file:/path-to-config-dir/
  • 不,仍在加载类路径文件:(
  • 如果可能,从类路径中删除 application.properties,然后尝试,因为对我有用。

标签: java spring command-line properties startup


【解决方案1】:

在你的属性类上做这样的事情:

 @Configuration
 @PropertySource(value = "file:${myapp.external.config}")

 **Command**  java -jar -Dmyapp.external.config="C:\yourPath\abc.properties" xyz.jar

如果你有多个外部属性文件,下面的例子

 @Configuration
 @PropertySource(value = {"file:${app1.config}", "file:${app2.config}"})

 **Command**  java -jar -Dapp1.config="C:\yourPath\abc1.properties" 
                        -Dapp2.config="C:\yourPath\abc2.properties" xyz.jar

【讨论】:

    【解决方案2】:

    这在 Windows 上对我有用:"C:\Program Files\Java\jdk-15.0.1\bin\java" -jar C:\Users\your.name\YourApp.jar --spring.config.location="C:/Users/your.name/yourAppProps.properties"

    【讨论】:

      猜你喜欢
      • 2012-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多