SpringBoot(四)之基础配置
文章目录
- SpringBoot(四)之基础配置
- 全局配置文件
- banner
- banner替换
- banner关闭
 
- 单个配置注入
- 系统配置注入
- 自定义配置
 
- 多个配置注入
- 自定义的配置的文件注入
- 命令行设置
- 环境配置(profile)
- 配置文件中,相互的属性的引入
 
 
全局配置文件
-  SpringBoot约定的resources目录(或者resources目录的下一级,如resources/config)下,创建 application.properties或者application.yml文件作为SpringBoot的全局配置文件。
-  可以在该文件中配置项目中需要用到的常量,分环境变量等信息,通过Spring将属性值注入到bean中。 
- application.properties文件格式
通过name=value的形式配置,如
spring.application.name=spring-boot-start
server.port=8080
- application.yml文件格式
**YAML(YAML Ain’t Markup Language)**是一种人类可读的数据序列化格式,通常用于配置文件和数据交换。YAML 使用空格缩进来表示层级关系,而不是像 XML 或 JSON 那样使用大括号或方括号。
以下是 YAML 文件的基本语法规则:
- 键值对: 使用冒号(:)分隔键和值,键值对之间使用冒号后面的空格进行分隔。
key1: value1
key2: value2
- 注释: 使用井号(#)表示注释。注释从井号开始一直到行尾。
# This is a comment
key1: value1  # This is another comment
- 列表: 使用短横线(-)表示列表项。列表项可以包含标量值、字典或嵌套列表。
fruits:- apple- orange- banana
- 嵌套结构: 使用缩进表示层级关系。子项的缩进必须比父项多两个空格。
person:name: Johnage: 30address:street: 123 Main Streetcity: Anytown
- 多行字符串: 使用管道符(|)表示多行字符串。换行符会被保留,但末尾的换行符会被忽略。
description: |This is a multi-linestring in YAML.
- 折叠的多行字符串: 使用大于符(>)表示折叠的多行字符串。换行符会被转换为空格,但末尾的换行符会被忽略。
description: >This is a foldedmulti-line string in YAML.
这些是 YAML 文件的基本语法规则。通过这些规则,你可以创建结构化、易读的配置文件或数据文件。
banner
项目启动时,有个默认的Spring官方banner图
  .   ____          _            __ _ _/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/  ___)| |_)| | | | | || (_| |  ) ) ) )'  |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/banner替换
替换步骤:
- 在resources目录下新建banner.txt,并降自己的图案粘贴进去,ASCII图案可通过网站http://www.network-science.de/ascii/一键生成
                    .__                  __
_____    _______  __|__|____    ____    |__|__ __  ____
\__  \  /  _ \  \/  /  \__  \  /  _ \   |  |  |  \/    \/ __ \(  <_> >    <|  |/ __ \(  <_> )  |  |  |  /   |  \
(____  /\____/__/\_ \__(____  /\____/\__|  |____/|___|  /\/            \/       \/      \______|          \/启动项目,观察console,默认的Spring已经被替换
                    .__                  __
_____    _______  __|__|____    ____    |__|__ __  ____
\__  \  /  _ \  \/  /  \__  \  /  _ \   |  |  |  \/    \/ __ \(  <_> >    <|  |/ __ \(  <_> )  |  |  |  /   |  \
(____  /\____/__/\_ \__(____  /\____/\__|  |____/|___|  /\/            \/       \/      \______|          \/2024-05-15 17:23:06.823  INFO 25432 --- [           main] c.a.s.SpringBootConfigApplication        : Starting SpringBootConfigApplication using Java 1.8.0_261 on DESKTOP-SQBHU59 with PID 25432 (D:\practise\spring-all\spring-boot-config\target\classes started by aoxiaojun in D:\practise\spring-all)
2024-05-15 17:23:06.825  INFO 25432 --- [           main] c.a.s.SpringBootConfigApplication        : No active profile set, falling back to 1 default profile: "default"
2024-05-15 17:23:07.372  INFO 25432 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2024-05-15 17:23:07.378  INFO 25432 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
- 如何增加项目名称或者项目版本号
在application.yml中定义application.title,application.version,application.description ,这个配置可以自定义。
利用占位符${application.title}形式替换,如在yaml中配置
application:title: spring boot configversion: 2.0description: spring-boot-config-test
并新增banner中占位符信息
                    .__                  __
_____    _______  __|__|____    ____    |__|__ __  ____
\__  \  /  _ \  \/  /  \__  \  /  _ \   |  |  |  \/    \/ __ \(  <_> >    <|  |/ __ \(  <_> )  |  |  |  /   |  \
(____  /\____/__/\_ \__(____  /\____/\__|  |____/|___|  /\/            \/       \/      \______|          \/:: ${application.title} ::                (${application.version})${application.description}
启动项目,观察console,响应的信息已经被打印出来
                    .__                  __
_____    _______  __|__|____    ____    |__|__ __  ____
\__  \  /  _ \  \/  /  \__  \  /  _ \   |  |  |  \/    \/ __ \(  <_> >    <|  |/ __ \(  <_> )  |  |  |  /   |  \
(____  /\____/__/\_ \__(____  /\____/\__|  |____/|___|  /\/            \/       \/      \______|          \/:: spring boot config ::                (2.0)spring-boot-config-test2024-05-15 17:25:55.586  INFO 4960 --- [           main] c.a.s.SpringBootConfigApplication        : Starting SpringBootConfigApplication using Java 1.8.0_261 on DESKTOP-SQBHU59 with PID 4960 (D:\practise\spring-all\spring-boot-config\target\classes started by aoxiaojun in D:\practise\spring-all)
2024-05-15 17:25:55.588  INFO 4960 --- [           main] c.a.s.SpringBootConfigApplication        : No active profile set, falling back to 1 default profile: "default"
banner关闭
- 可通过配置spring.main.banner-mode=off关闭banner
- 通过SpringApplication配置关闭banner
public static void main(String[] args) {SpringApplication springApplication = new SpringApplication(SpringBootConfigApplication.class);springApplication.setBannerMode(Banner.Mode.OFF);springApplication.run(args);
}
单个配置注入
通过Spring原生注解@Value(“${属性名}”)形式注入
系统配置注入
在TestController中,注入spring.application.name属性,并更改test控制器
@Value("${spring.application.name}")
private String applicationName;@GetMapping("/test")
public String test(){return "hello:	" + applicationName;
}
application.yml中配置spring.application.name的值
spring:application:name: spring-boot-config
访问localhost:8080/test
返回 hello: spring-boot-config
自定义配置
随意配置一个属性
any:attr:name: any-attr
通过@Value 在TestController中注入
@Value("${spring.application.name}")
private String applicationName;@Value("${any.attr.name}")
private String anyAttrName;@GetMapping("/test")
public String test(){return "hello:\t" + applicationName +"anyAttrName: " + anyAttrName;
}
多个配置注入
如果属性很多,且都属于同一个业务下面,则可以通过bean的形式将属性全部注入到一个bean的成员属性中。
- 定义接收到属性的bean
- 标注@Configuration注解表明该类是一个配置类
- 标注@ConfigurationProperties(prefix = “”),prefix配置的前缀。
如:
- 定义以下配置
config:user:name: zhangsanage: 18
- 新建ConfigBean类
@Configuration
@ConfigurationProperties(prefix = "config.user")
public class ConfigBean {private String name;private String age;...省略get set方法
}
如何使用?
 在其他Bean中通过注入ConfigBean的形式获取配置的信息。代码示例
	private final ConfigBean configBean;@Autowiredpublic TestController(ConfigBean configBean) {this.configBean = configBean;public void test(){System.out.println(configBean.getName() + configBean.getAge());}    
自定义的配置的文件注入
- 定义接收到属性的bean
- 标注@Configuration注解表明该类是一个配置类
- 标注@ConfigurationProperties(prefix = “”),prefix配置的前缀。
- 标注@PropertySource(“”),配置配置文件的源
如在resources目下新建test.properties文件,并配置
test.user.name=lisi
test.user.age=20
新建TestConfig
@Configuration
@ConfigurationProperties(prefix = "test.user")
@PropertySource("classpath:test.properties")
public class TestConfig {private String name;private String age;
}
命令行设置
可通过java -jar 命令配置
java -jar xxxx.jar --server.port=8081 //配置服务端口
环境配置(profile)
application.yml为主配置文件,如果要分环境,则需要创建 application-{profile}.yml的环境配置。
如application-dev.yml,appliction-prod.yml
通过在主配置文件中配置spring.profiles.active来启用对应的环境配置
spring:profiles:active: dev
配置文件中,相互的属性的引入
通过${配置名}占位符来引入其他的配置,如一下配置,any.attr.name引入了spring.application.name和server.port值。
spring:application:name: spring-boot-configserver:port: 8080
any:attr:name: ${spring.application.name} - ${server.port}