SpringBoot(四)之基础配置

简介: application.yml为主配置文件,如果要分环境,则需要创建 application-{profile}.yml的环境配置。

全局配置文件

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

2.pplication.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替换

替换步骤:


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

启动项目,观察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的成员属性中。


定义接收到属性的bean


标注@Configuration注解表明该类是一个配置类


标注@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());
    }    

自定义的配置的文件注入


定义接收到属性的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-config

server:
  port: 8080
any:
  attr:
    name: ${spring.application.name} - ${server.port}

目录
相关文章
Springboot项目启动的三种方式
Springboot项目启动的三种方式
833 0
xxl-job执行器启动报错读取不到配置文件Could not resolve placeholder ‘xxl.job.executor.address‘ in value “${xxl.job
有几个不用配置的属性,也要写出来,不填值就行 但是最后一个日志天数得写,写个-1。不然空字符串无法转成数字
|
1月前
|
前端开发 Java 应用服务中间件
《深入理解Spring》 Spring Boot——约定优于配置的革命者
Spring Boot基于“约定优于配置”理念,通过自动配置、起步依赖、嵌入式容器和Actuator四大特性,简化Spring应用的开发与部署,提升效率,降低门槛,成为现代Java开发的事实标准。
|
3月前
|
前端开发 Java jenkins
Jmeter压力测试工具全面教程和使用技巧。
JMeter是一个能够模拟高并发请求以检查应用程序各方面性能的工具,包括但不限于前端页面、后端服务及数据库系统。熟练使用JMeter不仅能够帮助发现性能瓶颈,还能在软件开发早期就预测系统在面对真实用户压力时的表现,确保软件质量和用户体验。在上述介绍的基础上,建议读者结合官方文档和社区最佳实践,持续深入学习和应用。
874 10
Unable to interpret the implicit parameter configuration with dataType: , dataTypeClass: class java.
Unable to interpret the implicit parameter configuration with dataType: , dataTypeClass: class java.
1071 0
|
5月前
|
SQL JSON 前端开发
较为完整的SpringBoot项目结构
本文介绍了SpringBoot项目的分层结构与目录组成。项目分为四层:**controller层**(前端交互)、**service层**(业务逻辑处理)、**dao层**(数据库操作)和**model层**(实体类定义)。分层设计旨在实现关注点分离,降低耦合度,提高系统灵活性、可维护性和扩展性。此外,还详细说明了项目目录结构,包括`controller`、`service`、`dao`、`entity`、`param`、`util`等子目录的功能划分,便于团队协作开发。此架构有助于前后端分离,明确各模块职责,符合高内聚低耦合的设计原则。
3629 1
|
Java 应用服务中间件 Maven
SpringBoot概述&SpringBoot基础配置&yml的使用&多环境启动
SpringBoot概述&SpringBoot基础配置&yml的使用&多环境启动
737 2
|
Java Spring 容器
SpringBoot读取配置文件的6种方式,包括:通过Environment、@PropertySource、@ConfigurationProperties、@Value读取配置信息
SpringBoot读取配置文件的6种方式,包括:通过Environment、@PropertySource、@ConfigurationProperties、@Value读取配置信息
2674 3
|
JavaScript 前端开发 Java
SpringBoot配置文件 —— 超详细全方位教程
本文是一篇关于SpringBoot配置文件的超详细全方位教程,涵盖了配置文件的作用、SpringBoot中的配置文件格式、优先级、properties和yml配置文件的详解及语法、读取配置文件的方法、转义字符和单双引号的使用、配置对象、集合和Map,以及yml的优缺点。
1680 0
SpringBoot配置文件 —— 超详细全方位教程
|
消息中间件 Java Kafka
springboot项目启动报错-案例情景介绍
springboot项目启动报错-案例情景介绍
579 2