SpringBoot(四)之基础配置

SpringBoot(四)之基础配置

全局配置文件

  • SpringBoot约定的resources目录(或者resources目录的下一级,如resources/config)下,创建application.properties或者application.yml文件作为SpringBoot的全局配置文件。

  • 可以在该文件中配置项目中需要用到的常量,分环境变量等信息,通过Spring将属性值注入到bean中。

  1. application.properties文件格式

通过name=value的形式配置,如

spring.application.name=spring-boot-start
server.port=8080
  1. application.yml文件格式

**YAML(YAML Ain’t Markup Language)**是一种人类可读的数据序列化格式,通常用于配置文件和数据交换。YAML 使用空格缩进来表示层级关系,而不是像 XML 或 JSON 那样使用大括号或方括号。

以下是 YAML 文件的基本语法规则:

  1. 键值对: 使用冒号(:)分隔键和值,键值对之间使用冒号后面的空格进行分隔。
key1: value1
key2: value2
  1. 注释: 使用井号(#)表示注释。注释从井号开始一直到行尾。
# This is a comment
key1: value1  # This is another comment
  1. 列表: 使用短横线(-)表示列表项。列表项可以包含标量值、字典或嵌套列表。
fruits:
  - apple
  - orange
  - banana
  1. 嵌套结构: 使用缩进表示层级关系。子项的缩进必须比父项多两个空格。
person:
  name: John
  age: 30
  address:
    street: 123 Main Street
    city: Anytown
  1. 多行字符串: 使用管道符(|)表示多行字符串。换行符会被保留,但末尾的换行符会被忽略。
description: |
  This is a multi-line
  string in YAML.
  1. 折叠的多行字符串: 使用大于符(>)表示折叠的多行字符串。换行符会被转换为空格,但末尾的换行符会被忽略。
description: >
  This is a folded
  multi-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 config
  version: 2.0
  description: spring-boot-config-test

并新增banner中占位符信息

                    .__                  __
_____    _______  __|__|____    ____    |__|__ __  ____
\__  \  /  _ \  \/  /  \__  \  /  _ \   |  |  |  \/    \
 / __ \(  <_> >    <|  |/ __ \(  <_> )  |  |  |  /   |  \
(____  /\____/__/\_ \__(____  /\____/\__|  |____/|___|  /
     \/            \/       \/      \______|          \/


    :: ${application.title} ::                (${application.version})
       ${application.description}

启动项目,观察console,响应的信息已经被打印出来

                    .__                  __
_____    _______  __|__|____    ____    |__|__ __  ____
\__  \  /  _ \  \/  /  \__  \  /  _ \   |  |  |  \/    \
 / __ \(  <_> >    <|  |/ __ \(  <_> )  |  |  |  /   |  \
(____  /\____/__/\_ \__(____  /\____/\__|  |____/|___|  /
     \/            \/       \/      \______|          \/


    :: spring boot config ::                (2.0)
       spring-boot-config-test

2024-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的成员属性中。

  1. 定义接收到属性的bean
  2. 标注@Configuration注解表明该类是一个配置类
  3. 标注@ConfigurationProperties(prefix = “”),prefix配置的前缀。

如:

  • 定义以下配置
config:
  user:
    name: zhangsan
    age: 18
  • 新建ConfigBean类
@Configuration
@ConfigurationProperties(prefix = "config.user")
public class ConfigBean {
    private String name;
    private String age;
	...省略get set方法
}

如何使用?

​ 在其他Bean中通过注入ConfigBean的形式获取配置的信息。代码示例

	private final ConfigBean configBean;

    @Autowired
    public TestController(ConfigBean configBean) {
        this.configBean = configBean;
        
    public void test(){
        System.out.println(configBean.getName() + configBean.getAge());
    }    

自定义的配置的文件注入

  1. 定义接收到属性的bean
  2. 标注@Configuration注解表明该类是一个配置类
  3. 标注@ConfigurationProperties(prefix = “”),prefix配置的前缀。
  4. 标注@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-config

server:
  port: 8080
any:
  attr:
    name: ${spring.application.name} - ${server.port}
  • 29
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值