iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >Spring Boot怎么读取自定义配置文件
  • 160
分享到

Spring Boot怎么读取自定义配置文件

2023-06-15 07:06:57 160人浏览 八月长安
摘要

这篇文章给大家分享的是有关Spring Boot怎么读取自定义配置文件的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。@Value首先,会想到使用@Value注解,该注解只能去解析yaml文件中的简单类型,并绑定到

这篇文章给大家分享的是有关Spring Boot怎么读取自定义配置文件的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

@Value

首先,会想到使用@Value注解,该注解只能去解析yaml文件中的简单类型,并绑定到对象属性中去。

felord:  phone: 182******32  def:    name: 码农小胖哥    blog: felord.cn    we-chat: MSW_623  dev:    name: 码农小胖哥    blog: felord.cn    we-chat: MSW_623  type: JUEJIN

对于上面的yaml配置,如果我们使用@Value注解的话,冒号后面直接有值的key才能正确注入对应的值。例如felord.phone我们可以通过@Value获取,但是felord.def不行,因为felord.def后面没有直接的值,它还有下一级选项。另外@Value不支持yaml松散绑定语法,也就是说felord.def.weChat获取不到felord.def.we-chat的值。

@Value是通过使用spring的SpEL表达式来获取对应的值的:

// 获取 yaml 中 felord.phone的值 并提供默认值 UNKNOWN@Value("${felord.phone:UNKNOWN}") private String phone;

@Value的使用场景是只需要获取配置文件中的某项值的情况下,如果我们需要将一个系列的值进行绑定注入就建议使用复杂对象的形式进行注入了。

@ConfigurationProperties

@ConfigurationProperties注解提供了我们将多个配置选项注入复杂对象的能力。它要求我们指定配置的共同前缀。比如我们要绑定felord.def下的所有配置项:

package cn.felord.yaml.properties; import lombok.Data;import org.springframework.boot.context.properties.ConfigurationProperties; import static cn.felord.yaml.properties.FelordDefProperties.PREFIX; @Data@ConfigurationProperties(PREFIX)public class FelordDefProperties {    static final String PREFIX = "felord.def";    private String name;    private String blog;    private String weChat;}

我们注意到我们可以使用weChat接收we-chat的值,因为这种形式支持从驼峰camel-case到短横分隔命名kebab-case的自动转换。

如果我们使用@ConfigurationProperties的话建议配置类命名后缀为Properties,比如Redis的后缀就是RedisProperties,RabbitMQ的为RabbitProperties。

另外我们如果想进行嵌套的话可以借助于@NestedConfigurationProperty注解实现。也可以借助于内部类。这里用内部类实现将开头yaml中所有的属性进行注入:

package cn.felord.yaml.properties; import lombok.Data;import org.springframework.boot.context.properties.ConfigurationProperties; import static cn.felord.yaml.properties.FelordProperties.PREFIX;  @Data@ConfigurationProperties(PREFIX)public class FelordProperties {     static final String PREFIX = "felord";    private Def def;    private Dev dev;    private Type type;     @Data    public static class Def {        private String name;        private String blog;        private String weChat;    }     @Data    public static class Dev {        private String name;        private String blog;        private String weChat;    }     public enum Type {        JUEJIN,        SF,        OSC,        CSDN    }}

单独使用@ConfigurationProperties的话依然无法直接使用配置对象FelordDefProperties,因为它并没有被注册为Spring Bean。我们可以通过两种方式来使得它生效。

显式注入 Spring ioc

你可以使用@Component、@Configuration等注解将FelordDefProperties注入Spring IoC使之生效。

package cn.felord.yaml.properties; import lombok.Data;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component; import static cn.felord.yaml.properties.FelordDefProperties.PREFIX; @Data@Component@ConfigurationProperties(PREFIX)public class FelordDefProperties {    static final String PREFIX = "felord.def";    private String name;    private String blog;    private String weChat;}

@EnableConfigurationProperties

我们还可以使用注解@EnableConfigurationProperties进行注册,这样就不需要显式声明配置类为Spring Bean了。

package cn.felord.yaml.configuration; import cn.felord.yaml.properties.FelordDevProperties;import org.springframework.boot.context.properties.EnableConfigurationProperties;import org.springframework.context.annotation.Configuration; @EnableConfigurationProperties({FelordDevProperties.class})@Configurationpublic class FelordConfiguration {}

该注解需要显式的注册对应的配置类。

@ConfigurationPropertiesScan

在Spring Boot 2.2.0.RELEASE中提供了一个扫描注解@ConfigurationPropertiesScan。它可以扫描特定包下所有的被@ConfigurationProperties标记的配置类,并将它们进行IoC注入。

package cn.felord.yaml; import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.context.properties.ConfigurationPropertiesScan;import org.springframework.boot.context.properties.EnableConfigurationProperties; @ConfigurationPropertiesScan@SpringBootApplicationpublic class SpringBootYamlApplication {     public static void main(String[] args) {        SpringApplication.run(SpringBootYamlApplication.class, args);    } }

这非常适合自动注入和批量注入配置类的场景,但是有版本限制,必须在2.2.0及以上。

@PropertySource注解

@PropertySource可以用来加载指定的配置文件,默认它只能加载*.properties文件,不能加载诸如yaml等文件。

@PropertySource相关属性介绍

  • value:指明加载配置文件的路径。

  • ignoreResourceNotFound:指定的配置文件不存在是否报错,默认是false。当设置为 true 时,若该文件不存在,程序不会报错。实际项目开发中,最好设置 ignoreResourceNotFound 为 false。

  • encoding:指定读取属性文件所使用的编码,我们通常使用的是UTF-8。

@Data@AllArgsConstructor@NoArgsConstructor@Builder@Configuration@PropertySource(value = {"classpath:common.properties"},ignoreResourceNotFound=false,encoding="UTF-8")@ConfigurationProperties(prefix = "author")public class Author {    private String name;    private String job;    private String sex;}

有小伙伴也许发现示例上的@ConfigurationProperties注解了。当我们使用@Value需要注入的值较多时,代码就会显得冗余。我们可以使用@ConfigurationProperties 中的 prefix 用来指明我们配置文件中需要注入信息的前缀

前边提到了用@PropertySource只能加载*.properties文件,但如果我们项目的配置文件不是*.properties这种类型,而是其他类型,诸如yaml,此时我们可以通过实现PropertySourceFactory接口,重写createPropertySource方法,就能实现用@PropertySource也能加载yaml等类型文件。

public class YamlPropertySourceFactory implements PropertySourceFactory {    @Override    public PropertySource<?> createPropertySource(String sourceName, EncodedResource resource) throws IOException {        Properties propertiesFromYaml = loadYaml(resource);        if(StringUtils.isBlank(sourceName)){            sourceName =  resource.getResource().getFilename();;        }        return new PropertiesPropertySource(sourceName, propertiesFromYaml);    }    private Properties loadYaml(EncodedResource resource) throws FileNotFoundException {        try {            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();            factory.setResources(resource.getResource());            factory.afterPropertiesSet();            return factory.getObject();        } catch (IllegalStateException e) {            // for ignoreResourceNotFound            Throwable cause = e.getCause();            if (cause instanceof FileNotFoundException)                throw (FileNotFoundException) e.getCause();            throw e;        }    }}
@Data@AllArgsConstructor@NoArgsConstructor@Builder@Configuration@PropertySource(factory = YamlPropertySourceFactory.class,value = {"classpath:user.yml"},ignoreResourceNotFound=false,encoding="UTF-8")@ConfigurationProperties(prefix = "user")public class User {    private String username;    private String passWord;}

使用EnvironmentPostProcessor加载自定义配置文件

实现EnvironmentPostProcessor接口,重写postProcessEnvironment方法

@Slf4jpublic class CustomEnvironmentPostProcessor implements EnvironmentPostProcessor {    @Override    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {        Properties properties = new Properties();        try {            properties.load(new InputStreamReader(CustomEnvironmentPostProcessor.class.getClassLoader().getResourceAsStream("custom.properties"),"UTF-8"));            PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource("custom",properties);            environment.getPropertySources().addLast(propertiesPropertySource);        } catch (IOException e) {          log.error(e.getMessage(),e);        }    }}

在META-INF下创建spring.factories

spring.factories文件内容如下:org.springframework.boot.env.EnvironmentPostProcessor=com.GitHub.lybgeek.env.CustomEnvironmentPostProcessor

2步骤实现完后,就可以在代码中直接用@Value的方式获取自定义配置文件内容了

读取的自定义配置文件内容的实现方法有多种多样,除了上面的方法,还可以在以-jar方式启动时,执行形如下命令

java -jar project.jar --spring.config.location=classpath:/config/custom.yml

也能实现。还可以干脆自定义配置文件都以application-*为前缀,比如application-custom,然后在application.properties,使用spring.profiles.include=custom或者spring.profiles.active=custom也可以实现

感谢各位的阅读!关于“Spring Boot怎么读取自定义配置文件”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

--结束END--

本文标题: Spring Boot怎么读取自定义配置文件

本文链接: https://www.lsjlt.com/news/278477.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Spring Boot怎么读取自定义配置文件
    这篇文章给大家分享的是有关Spring Boot怎么读取自定义配置文件的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。@Value首先,会想到使用@Value注解,该注解只能去解析yaml文件中的简单类型,并绑定到...
    99+
    2023-06-15
  • Spring Boot读取自定义配置文件
    目录@Value @ConfigurationProperties 显式注入 Spring IoC @EnableConfigurationProperties @Configura...
    99+
    2024-04-02
  • Spring Boot怎么正确读取配置文件属性
    这篇“Spring Boot怎么正确读取配置文件属性”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Spring&n...
    99+
    2023-06-30
  • Springboot读取配置文件及自定义配置文件的方法
    1.创建maven工程,在pom文件中添加依赖<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring...
    99+
    2023-05-30
    spring boot 配置文件
  • SpringBoot读取自定义配置文件方式(properties,yaml)
    目录一、读取系统配置文件application.yaml二、读取自定义配置文件properties格式内容三、读取自定义配置文件yaml格式内容四、其他扩展内容一、读取系统配置文件a...
    99+
    2024-04-02
  • spring-boot如何读取props和yml配置文件
    这篇文章主要介绍spring-boot如何读取props和yml配置文件,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!最近微框架spring-boot很火,笔者也跟风学习了一下,废话不多说,现给出一个读取配置文件的例...
    99+
    2023-05-30
    spring boot props
  • spring boot装载自定义yml文件
    yml格式的配置文件感觉很人性化,所以想把项目中的.properties都替换成.yml文件,主要springboot自1.5以后就把@configurationProperties中的location参数去掉,各种查询之后发现可以用Yam...
    99+
    2023-05-31
    spring boot yml
  • 在SpringBoot下如何读取自定义properties配置文件
    这篇文章将为大家详细讲解有关在SpringBoot下如何读取自定义properties配置文件,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。SpringBoot工程默认读取application.prop...
    99+
    2023-05-30
    spring boot properties
  • Spring Boot读取Yml配置文件的3种方法
    简述: 项目开发中难免要读取配置文件,本文结合开发经验介绍几种使用过的读取配置文件的方法。 1.基础用法,使用注解@Autowired注入Environment类 这种方式比较常见,就像注入service或者dao一样,声明一个Env...
    99+
    2023-09-03
    spring boot java spring Powered by 金山文档
  • Spring Boot 如何正确读取配置文件属性
    目录前言@Value示例代码@ConfigurationProperties示例代码@EnableConfigurationProperties@ConfigurationPrope...
    99+
    2024-04-02
  • Spring boot读取外部化怎么配置
    本篇内容主要讲解“Spring boot读取外部化怎么配置”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Spring boot读取外部化怎么配置”吧!1. Propertie...
    99+
    2023-06-29
  • spring boot如何实现自定义配置源
    这篇文章给大家分享的是有关spring boot如何实现自定义配置源的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。概述我们知道,在Spring boot中可以通过xml或者@ImportResource 来引入自...
    99+
    2023-05-30
    springboot
  • spring boot怎么获取配置文件的属性
    这篇文章主要介绍“spring boot怎么获取配置文件的属性”,在日常操作中,相信很多人在spring boot怎么获取配置文件的属性问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”spring boot怎么...
    99+
    2023-06-05
  • properties配置文件如何使用Spring Boot进行读取
    这篇文章给大家介绍properties配置文件如何使用Spring Boot进行读取,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。在SpringApplication类中: private ConfigurableE...
    99+
    2023-05-31
    springboot properties
  • Spring Boot如何读取自定义外部属性详解
    测试的环境:Spring Boot2 + Maven +lombok 准备需要用到的基础类: public class People { private String n...
    99+
    2024-04-02
  • Spring boot 自定义 Starter及自动配置的方法
    目录Starter 组件简介自定义 Starter 组件Starter 组件使用 StarterStarter 传参自身与第三方维护Starter 组件简介 Starter 组件是 ...
    99+
    2022-12-08
    Spring boot 自定义 Starter Spring boot自动配置
  • 详解Spring Boot中如何自定义SpringMVC配置
    目录前言一、SpringBoot 中 SpringMVC 配置概述二、WebMvcConfigurerAdapter 抽象类三、WebMvcConfigurer 接口四、WebMvc...
    99+
    2024-04-02
  • Spring Boot自定义Starter组件开发实现配置过程
    目录自定义starter为什么要自定义starter自定义starter的命名规则实现方法引入依赖编写测试类创建配置类创建spring.factories文件乱码问题解决方案:1. ...
    99+
    2024-04-02
  • 怎么解决springboot读取自定义配置文件时出现乱码问题
    这篇文章主要介绍“怎么解决springboot读取自定义配置文件时出现乱码问题”,在日常操作中,相信很多人在怎么解决springboot读取自定义配置文件时出现乱码问题问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家...
    99+
    2023-06-25
  • .NETCore自定义配置文件
    前文讲获取配置文件内容的时候,是获取默认的appsettings.json配置文件的配置,下面说明下如何进行自定义配置文件获取 1. Json Provider 1.1 构建独立的I...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作