springboot能自动读取配置文件|SpringBoot有几种读取配置的方式

|

① 请教,如何spring boot里动态读取配置文件

项目,需要访问多个数据库,而且需要在服务器运行不重新启动的情况下,动态的修改spring中配置的数据源datasource,在网上找了很多资料,最后找到了适合我的方法,下面总结一下。 spring的配置文件是在容器启动的时候就加载到内存中的

② SpringBoot自动配置的原理及实现/SpringBoot之@Import注解正确使用方式

https://www.jianshu.com/p/6b2f672e2446 了解SpringBoot之@Import注解正确使用方式 SpringBoot 的核心就是自动配置,自动配置又是基于条件判断来配置 Bean。关于自动配置的源码在 spring-boot -autoconfigure-2.0.3.RELEASE.jar 在通常需要我们在 property 中配置信息时,通常使用 @ConfigurationProperties(pefix=“前缀”) 注解的方式从配置文件中获取配置,如下: application.yml 中配置信息 访问 url 获取配置信息返回的值 http://localhost:8080/msg 如果把 application.yml 中的配置信息注释掉则默认使用 default 值,否则使用配置信息中的值,以上便是普通配置方式 SpringBoot 运行原理 先看 @SpringBootApplication 主要关注的几个注解如下 @SpringBootConfiguration:标记当前类为配置类 @EnableAutoConfiguration:开启自动配置 @ComponentScan:扫描主类所在的同级包以及下级包里的 Bean 关键是 @EnableAutoConfiguration 最关键的要属 @Import(.class),借助** **,@EnableAutoConfiguration 可以帮助 SpringBoot 应用将所有符合条件的 @Configuration 配置都加载到当前 SpringBoot 创建并使用的 IoC 容器: 通过 @Import(.class) 导入的配置功能, 中的方法 getCandidateConfigurations,得到待配置的 class 的类名集合, 这个集合就是所有需要进行自动配置的类,而是是否配置的关键在于 META-INF/spring.factories 文件中是否存在该配置信息 打开,如下图可以看到所有需要配置的类全路径都在文件中,每行一个配置,多个类名逗号分隔, 而 \ 表示忽略换行 整个流程如上图所示 以 类来看其主要构成部分 都能看到各种各样的条件判断注解,满足条件时就加载这个 Bean 并实例化 此类的条件注解是:@ConditionalOnProperty @ConditionalOnBean:当容器里有指定 Bean 的条件下 @ConditionalOnClass:当类路径下有指定的类的条件下 @ConditionalOnExpression:基于 SpEL 表达式为 true 的时候作为判断条件才去实例化 @ConditionalOnjava:基于 JVM 版本作为判断条件 @ConditionalOnJndi:在 JNDI 存在的条件下查找指定的位置 @ConditionalOnMissingBean:当容器里没有指定 Bean 的情况下 @ConditionalOnMissingClass:当容器里没有指定类的情况下 @ConditionalOnWebApplication:当前项目时 Web 项目的条件下 @:当前项目不是 Web 项目的条件下 @ConditionalOnProperty:指定的属性是否有指定的值 @ConditionalOnResource:类路径是否有指定的值 @:当指定 Bean 在容器中只有一个,或者有多个但是指定首选的 Bean 这些注解都组合了 @Conditional 注解,只是使用了不同的条件组合最后为 true 时才会去实例化需要实例化的类,否则忽略 这种 spring4.X 带来的动态组合很容易后期配置,从而避免了硬编码,使配置信息更加灵活多变,同时也避免了不必要的意外异常报错。使用的人只要知道配置的条件即可也不用去阅读源码,方便快捷,这也是 sprignboot 快捷方式带来的好处 参考 HttpEncodingAutoConfiguration 配置信息如下 案例扩展 项目 需要实例化的服务类 配置信息对应的属性映射类, 需要 pom 中加入 spring-boot-starter 依赖 自动配置文件 在创建如下路径文件 src/main/resources/META-INF/spring.factories 必须是自动配置类的全路径 mvn install 该项目 创建一个 springboot-mvc 项目 pom 依赖上面的 jar http://localhost:8080 / 则返回当前服务的默认值 在 applicaton.yml 中加, 重启刷新则会更新为如下信息 SpringBoot 自动化配置关键组件关系图 mybatis-spring-boot-starter、spring-boot-starter-web 等组件的 META-INF 文件下均含有 spring.factories 文件,自动配置模块中,SpringFactoriesLoader 收集到文件中的类全名并返回一个类全名的数组,返回的类全名通过反射被实例化,就形成了具体的工厂实例,工厂实例来生成组件具体需要的 bean。 在 spring boot 中有时候需要控制配置类是否生效, 可以使用 @ConditionalOnProperty 注解来控制 @Configuration 是否生效.

③ Springboot打成JAR包后读取外部配置文件

Springboot的application.properties配置文件的加载路径优先歼念蔽级(从高到低):

当Springboot打成JAR包(不包含配置文件),读取外部配高薯置文件application.properties时,氏州可以选择:

④ SpringBoot 如何优雅读取配置文件10分钟教你搞定

很多时候我们需要将一些常用的配置信息比如阿里云 oss 配置、发送短信的相关信息配置等等放到配置文件中。 下面我们来看一下 Spring 为我们提供了哪些方式帮助我们从配置文件中读取这些配置信息。 application.yml 内容如下: wuhan2020: 2020年初武汉爆发了新型冠状病毒,疫情严重,但是,我相信一切都会过去!武汉加油!中国加油!my-profile:name: Guide哥email: [email protected]:location: 湖北武汉加油中国加油books:    -name: 天才基本法description: 二十二岁的林朝夕在父亲确诊阿尔茨海默病这天,得知自己暗恋多年的校园男神裴之即将出国深造的消息——对方考取的学校,恰是父亲当年为她放弃的那所。    -name: 时间的秩序description: 为什么我们记得过去,而非未来?时间“流逝”意味着什么?是我们存在于时间之内,还是时间存在于我们之中?卡洛·罗韦利用诗意的文字,邀请我们思考这一亘古难题——时间的本质。    -name: 了不起的我description: 如何养成一个新习惯?如何让心智变得更成熟?如何拥有高质量的关系? 如何走出人生的艰难时刻? 1.通过 @value 读取比较简单的配置信息 使用 @Value("${property}") 读取比较简单的配置信息: @Value("${wuhan2020}")String wuhan2020; 需要注意的是 @value这种方式是不被推荐的,Spring 比较建议的是下面几种读取配置信息的方式。 2.通过@ConfigurationProperties读取并与 bean 绑定 LibraryProperties 类上加了 @Component 注解,我们可以像使用普通 bean 一样将其注入到类中使用。 importlombok.Getter;importlombok.Setter;importlombok.ToString;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.context.annotation.Configuration;importorg.springframework.stereotype.Component;importjava.util.List;@[email protected](prefix ="library")@[email protected]@{privateString location;privateList books;@[email protected]@ToStringstaticclassBook{        String name;        String description;    }} 这个时候你就可以像使用普通 bean 一样,将其注入到类中使用: packagecn.javaguide.readconfigproperties;importorg.springframework.beans.factory.InitializingBean;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;/** *@authorshuang.kou */@ntsInitializingBean{privatefinalLibraryProperties library;(LibraryProperties library){this.library = library;    }publicstaticvoidmain(String[] args){        SpringApplication.run(.class,args);    }@(){        System.out.println(library.getLocation());        System.out.println(library.getBooks());    }} 控制台输出: 湖北武汉加油中国加油[LibraryProperties.Book(name=天才基本法, description……..] 3.通过@ConfigurationProperties读取并校验 我们先将application.yml修改为如下内容,明显看出这不是一个正确的 email 格式: my-profile:name: Guide哥email: koushuangbwcx@ ProfileProperties 类没有加 @Component 注解。我们在我们要使用ProfileProperties 的地方使用@ EnableConfigurationProperties注册我们的配置 bean: importlombok.Getter;importlombok.Setter;importlombok.ToString;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.stereotype.Component;importorg.springframework.validation.annotation.Validated;importjavax.validation.constraints.Email;importjavax.validation.constraints.NotEmpty;/***@authorshuang.kou*/@[email protected]@[email protected]("my-profile")@{@NotEmptyprivateString name;@[email protected] email;//配置文件中没有读取到的话就用默认值privateBooleanhandsome =Boolean.TRUE;} 具体使用: packagecn.javaguide.readconfigproperties;importorg.springframework.beans.factory.InitializingBean;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.boot.context.properties.EnableConfigurationProperties;/** *@authorshuang.kou */@[email protected](ProfileProperties.class){privatefinalProfileProperties profileProperties;(ProfileProperties profileProperties){this.profileProperties = profileProperties;    }publicstaticvoidmain(String[] args){        SpringApplication.run(.class,args);    }@(){        System.out.println(profileProperties.toString());    }} 因为我们的邮箱格式不正确,所以程序运行的时候就报错,根本运行不起来,保证了数据类型的安全性: Binding to target org.springframework.boot.context.properties.bind.BindException:Failedtobindpropertiesunder'my-profile'to cn.javaguide.readconfigproperties.ProfileProperties failed:Property:my-profile.emailValue:[email protected]:classpathresource[application.yml]:5:10Reason:mustbeawell-formedemailaddress 我们把邮箱测试改为正确的之后再运行,控制台就能成功打印出读取到的信息: ProfileProperties(name=Guide哥, [email protected], handsome=true) [email protected]读取指定 properties 文件 importlombok.Getter;importlombok.Setter;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.PropertySource;importorg.springframework.stereotype.Component;@[email protected]("classpath:website.properties")@[email protected]{@Value("${url}")privateString url;} 使用: @Autowiredprivate WebSite webSite;System.out.println(webSite.getUrl());//https://javaguide.cn/ 5.题外话:Spring 加载配置文件的优先级 Spring 读取配置文件也是有优先级的,直接上图:原文链接:https://www.toutiao.com/a6791445278911103500/?log_from=7f5fb8f9b4b47_1640606437752

⑤ SpringBoot有几种读取配置的方式

常见的读取配置的方式有三种:第一、@Value注解,比较常用的一种方式。也支持与@propertySource注解何用,指定使用的配置文件第二、@Configuration注解,读取配置到类中,批量注入配置属性第三、Environment对象,获取配置文件中所有的属性的对象如果你想掌握时下热门微服务技术栈,跟上时代技术步伐,就去黑马程序员官网视频库看免费视频。


赞 (0)