Spring boot如何读取jar外的属性文件 [英] Spring boot how to read properties file outside jar

查看:23
本文介绍了Spring boot如何读取jar外的属性文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的目标文件夹中,有 2 个文件夹,lib 和 conf.所有的properties文件都放在conf文件夹中,jars放在lib文件夹中.

in my target folder, there are 2 folders, lib and conf. all the properties files are placed in conf folder, and jars are placed in lib foulder.

在spring boot之前,我们在spring.xml中使用以下配置来使用@value

previous to spring boot, we use following configuration in spring.xml to use @value

<context:property-placeholder location="classpath*:*.properties"/>

在java代码中,如:

and in java code like:

@Value("${name}")

private String name;

但是在spring boot中,我不知道如何在java代码中做同样的事情.

but in spring boot, i don't know how to do the same in java code.

我尝试了以下操作,但不起作用

i have tried following, but not work

@Configuration
@PropertySource(value = "classpath:aaa.properties")
public class AppConfig {
    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
    }
}

推荐答案

我对问题的标题和描述有点困惑.希望我的评论不会让您更加困惑.

I'm a bit confused by the title of the question and the description. Hopefully I won't confuse you even more with my comments.

总的来说,Spring Boot 对项目结构以及创建的二进制文件非常有意见.推荐的方式(Spring Boot 意见)是构建一个包含所有依赖的 jar(fat jar).如果您需要在您的胖 jar 之外定义配置属性(或者战争,如果这是您构建的),Spring Boot 提供了许多选项(请参阅参考资料 1).我喜欢我的应用程序使用可以使用系统属性设置的标志 (spring.config.location) 指向外部文件:

In general, Spring Boot is VERY opiniated about project structure as well as the binary created. The recomended way (Spring Boot opinion) is to build a jar with all dependencies inside (fat jar). If you need configuration properties defined outside your fat jar (or war if that's what you built), Spring Boot offers many options (see reference 1). I like my apps to point to an external file using the flag (spring.config.location) which can be set with a system property:

java -jar -Dspring.config.location=<path-to-file> myBootProject.jar

请注意,您可以通过使用环境变量来定义外部文件所在的位置来执行类似操作.

Notice that you can do something similar by using an environment variable to define where your external file lives.

我希望这会有所帮助!

参考资料:1. https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

这篇关于Spring boot如何读取jar外的属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆