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

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

问题描述

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

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;

但是在春季启动中,我不知道如何在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(胖jar).如果您需要在胖子外定义的配置属性(或者如果这是您构建的,则定义war),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天全站免登陆