Springboot

您所在的位置:网站首页 springboot读取配置文件中的常量 Springboot

Springboot

#Springboot| 来源: 网络整理| 查看: 265

在SpringBoot中我们一般都会用到配置文件:application.properties或application.yml,用于存放一些配置信息,例如:数据库的连接信息等,我们来看下配置文件的相关内容。

一、常见位置

在SpringBoot中常见存放application配置文件有4种地方,分别是:

1、项目根目录下创建【config】目录,并存放配置文件

2、在项目根目录下直接创建配置文件

3、在【resources】目录下创建【config】目录,并存放配置文件

4、在【resources】中直接创建配置文件

这四个位置的加载顺序权限,依次减低,即先读取1顺序往下。如图:

二、ideal自定义文件位置

在ideal中可以直接设置自定义配置文件目录。如图:

编辑启动项,在【Environment variables】中添加【spring.config.location=classpath:/】或【spring.config.additional-location=classpath:/ 】或【spring.config.name=java】,在【resources】下创建目录并添加配置文件。

spring.config.location:表示自己重新定义配置文件的位置,项目启动时就按照定义的位置去查找配置文件,这种定义方式会覆盖掉默认的四个位置

spring.config.additional-location:表示在四个位置的基础上,再添加几个位置,新添加的位置的优先级大于原本的位置.

spring.config.name:直接指定【resources】下配置文件,且自定义文件名称。

三、启动时指定配置文件

即在项目打成jar包后,使用命令进行指定配置文件。

java -jar myproject.jar --spring.config.name=app 复制代码

app即配置文件的名称,且可以不带上后缀名称

四、通过@PropertySource指定

SpringBoot中使用了@PropertySource来代替Spring中xml中的

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

@Component @PropertySource("classpath:xxxx.properties") //指定resources下的xxxx.properties文件 public class User{ @Value("${userName}") private String userName; } 复制代码

注:yml配置文件不支持该注解

4.1 读取自定义yml格式配置文件 4.1.1 自定义加载yml类 /** * @author: jiangjs * @description: * @date: 2022/12/29 14:46 **/ public class DefinedYmlConfigFactory extends DefaultPropertySourceFactory { @Override public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException { String sourceName = Objects.nonNull(name) ? name: resource.getResource().getFilename(); return !resource.getResource().exists() ? new PropertiesPropertySource(sourceName, new Properties()) : sourceName.endsWith(".yml") || sourceName.endsWith(".yaml") ? new PropertiesPropertySource(sourceName, this.loadYamlConfig(resource)) : super.createPropertySource(name,resource); } private Properties loadYamlConfig(EncodedResource resource){ YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean(); factoryBean.setResources(resource.getResource()); factoryBean.afterPropertiesSet(); return factoryBean.getObject(); } } 复制代码 4.1.2 指定@PropertySource的factory @Data @PropertySource(value = "classpath:user.yml",factory = DefinedYmlConfigFactory.class) @Component public class UserInfo { @Value("${userinfo.user_name}") private String userName; @Value("${userinfo.login_name}") private String loginName; @Value("${userinfo.gender}") private String gender; } 复制代码 五、类型安全注入

多属性时,使用@Value获取值比较麻烦,工作量大,因此可以采用@ConfigurationProperties(),用以减轻工作,减少工作量。

@Component @PropertySource("classpath:xxxx.properties") @ConfigurationProperties(prefix = "xxxx") public class Book { private String userName; } 复制代码

注:代码中配置以“xxxx”为前缀的属性,而属性名必须与配置文件中的属性名保持一致,或骆驼命名方式。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3