简单类型:(8个基本类型/String/Date)

107 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第20天,点击查看活动详情

简单类型:(8个基本类型/String/Date)

@PropertySource:默认会加载application.properties/application.yml文件中的数据; 例如@PropertySource(value={"classpath:conf.properties"})加载conf.properties文件中的数据; 但是,@PropertySource只能加载properties,不能加载yml

@ImportResource spring boot自动装配/自动配置. spring等配置文件 默认会被spring boot自动给配置好。 如果要自己编写spring等配置文件, spring boot能否识别? 默认不识别。 如果需要识别,则需要在spring boot主配置类上 通过@ImportResource指定配置文件的路径

但是不推荐手写spring配置文件。 配置:xml配置文件,通过注解配置。 spring boot推荐时候用注解方式进行配置:写类,@Configuration @Bean ,示例:

spring boot全局配置文件中的 占位符表达式 a.随机数 random.uuidb.引用变量值yml中:student:name:{random.uuid}等 b.引用变量值 yml中: student: name: {student.user.name}

实际引用的是properties中的student.user.name=zl67

yml中: student: name: ${student.user.name2:无名} 13.多环境的切换(profile) a. properties 默认boot会读取application.properties环境8882 多个: application-环境名.properties application-dev.properties8883 application-test.properties8884

如果要选择某一个具体的环境: application.properties中指定:spring.profiles.active=环境名

如果将application.properties注释掉,spring boot仍然会读取其他appilcation-环境名.properties中的配置。并且properties的优先级高于yml

b.yml 第一个环境(主环境) server: port: 8883 spring: profiles: active: dev 指定本次采用的环境 第二个环境

server: port: 8884 spring: profiles: dev 环境名

c.动态切换环境 i:通过运行参数指定环境 (1)STS(Eclipse) :Run Configuration - Argument - program Argument --spring.profiles.active=环境名 (2)命令行方式: java -jar 项目名.jar --spring.profiles.active=环境名 ii:通过vm参数指定环境 STS(Eclipse) :Run Configuration - Argument - VM -Dspring.profiles.active=环境名

13.配置文件的位置

i.项目内部的配置文件:

properties和yml中的配置,相互补充;如果冲突,则properties优先级高。 spring boot默认能够读取的application.properties/application.yml,这2个文件 可以存在于以下4个地方: file:项目根目录/config application.properties file:项目根目录 application.properties classpath:项目根目录/config application.properties classpath:项目根目录 application.properties

注意: a.如果某项配置冲突,则优先级从上往下 b.如果不冲突,则互补结合使用

配置项目名: properties文件中 server.servlet.context-path=/boot

ii.项目外部的配置文件: (补救)

在项目Run configuration ,argumenets: --spring.config.location=D:/application.properties 如果 同一个配置 同时存在于 内部配置文件 和外部配置文件,则外部>内部

HW.jar 运行,8881--8882 外部配置文件 通过命令行 调用外部配置文件 java -jar 项目.jar --spring.config.location=D:/application.properties

iii.项目运行参数: (补救)

在项目Run configuration ,argumenets: --server.port=8883 通过命令行 调用外部配置文件 java -jar 项目.jar --server.port=8883

多个地方配置时,如果冲突,优先级: 命令参数(调用外部的配置文件 > 运行参数 )>内部文件 (properties>yaml)