【问题标题】:Spring External Config Location doesn't workSpring 外部配置位置不起作用
【发布时间】:2018-09-17 05:48:30
【问题描述】:

我有以下部署结构:

├── bin
│   ├── stop.sh
│   └── start.sh
├── config
│   ├── application-dev.properties
│   ├── application-local.properties
│   ├── application.properties
│   └── logback.xml
├── lib
    ├── myjar.jar
|__ logs

....

我的启动脚本是这样的:

jar -jar ../lib/myjar.jar --spring.profiles.active=dev --spring.config.location=file:./../config/

活动配置文件被拾取,但似乎 spring.config.location 被忽略并从打包的 jar 中获取。

我在这里阅读了有关外部配置的所有信息 - https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html,但我尝试了一些变体,包括类路径,例如)

--spring.config.location=file:./../config/,classpath:/

但这只是行不通。我也尝试过使用 -D 选项,但这也不起作用。

感谢您的帮助

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    使用参数从 jar 运行命令:

    java -jar -Dfile.location=myfile.properties your_app.jar
    

    在您的应用程序中您可以获得价值:

    System.getProperty("file.location");
    

    以及完整的示例类配置:

    @Configuration
    @ComponentScan
    public class MyConfig{
    
        @Bean
        public static PropertySourcesPlaceholderConfigurer properties2() throws IOException {
            PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
            PropertiesFactoryBean properties = new PropertiesFactoryBean();
    
            Resource resource = new FileSystemResource(System.getProperty("file.location"));
    
            properties.setLocation(resource);
            propertySourcesPlaceholderConfigurer.setProperties(properties.getObject());
            return propertySourcesPlaceholderConfigurer;
        }
    
    }
    

    在类(@Component 并对其进行扩展)中,您可以使用属性文件中的变量:

    @Value("${myperty.host}")
    private String host;
    

    【讨论】:

    • 我真的不想更改代码和修改系统属性,特别是因为 spring 应该支持这一点。这个例子还指定了一个具体的属性文件,这意味着我失去了默认属性 spring 提供的继承。谢谢
    猜你喜欢
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 2011-09-20
    • 1970-01-01
    相关资源
    最近更新 更多