有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从命令行设置spring属性文件位置

我有一个简单的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,我只想以某种方式设置属性文件的位置。有什么想法吗?这有可能吗


共 (2) 个答案

  1. # 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. # 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"