springboot入门及application.yaml核心配置文件


springboot入门及application.yaml核心配置文件

什么是SpringBoot

SpringBoot是由Pivotal团队在2013年开始研发、2014年4月发布第一个版本的全新开源的轻量级框架。springboot是一个快速开发的框架,可以迅速搭建一套基于spring框架体系的应用。

SpringBoot优点

  1. 独立运行Spring项目

    Spring boot 可以以jar包形式独立运行,运行一个Spring Boot项目只需要通过java -jar xx.jar来运行

  2. 内嵌servlet容器

    Spring Boot可以选择内嵌Tomcat、jetty或者Undertow,这样我们无须以war包形式部署项目

  3. 提供starter简化Maven配置

    spring提供了一系列的start pom来简化Maven的依赖加载

  4. 自动装配Spring

    SpringBoot会对SpringBoot启动类的子包下的类进行自动装配

  5. 准生产的应用监控

    SpringBoot提供基于http ssh telnet对运行时的项目进行监控

  6. 无代码生产和xml配置

    SpringBoot不是借助与代码生成来实现的,而是通过条件注解来实现的

什么是微服务

? 微服务是一种用于构建应用的架构方案。微服务架构有别于更为传统的单体式方案,可将应用拆分为多个核心功能。每个功能都被称为一项服务,可以单独构建和部署,各项服务在工作式不会相互印象

springboot与微服务的关系

? spring Cloud依赖于springboot,spring boot专注于快速开发个体微服务,spring Cloud是关注全局的微服务协调治理框架


SpringBoot入门

  1. New Project

  2. 点击Spring Initializr

  3. 创建项目名称(jdk版本、及包名等)

  4. 场景依赖选择界面

  5. 存放位置

  6. springboot项目会默认生成项目启动类、存放静态资源和页面的文件夹、编写项目配置的配置文件以及进行项目单元测试的测试类

  7. 查看自动生成的启动类

    package com.sheep;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class DemoApplication {
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    }
    

    @SpringBootApplication:表示当前类SpringBoot的入口,Application类的存放位置必须是其他相关业务类的存放位置的父级。

  8. pom.xml中查看自动生成添加的依赖

    <?xml version="1.0" encoding="UTF-8"?>
    
        4.0.0
        
            org.springframework.boot
            spring-boot-starter-parent
            2.4.5
             
        
        com.sheep
        demo
        0.0.1-SNAPSHOT
        demo
        sheep Spring Boot project
        
            11
        
        
            
                org.springframework.boot
                spring-boot-starter-web
            
            
                org.springframework.boot
                spring-boot-starter-test
                test
            
        
        
            
                
                    org.springframework.boot
                    spring-boot-maven-plugin
                
            
        
    
    

    springboot依赖管理:

    ? spring-boot-starter-parent:在spring-boot-starter-parent的父依赖spring-boot-dependencies中对框架 的依赖文件进行了统一版本号管理;

    启动器:

    ? spring-boot-starter-web:web依赖启动器,添加后springboot框架会自动将web所依赖的包全部导入

    ? spring-boot-devtools:热部署依赖启动器,· · · devtools所依赖的包全部导入

    ? spring-boot-starter-test:单元测试依赖启动器,· · · test所依赖的包全部导入

    ? 单元测试中的注解:

    ? @RunWith(SpringRunner.class) //测试运行器,并加载SpringBoot测试注解

    ? @SpringBootTest //标记单元测试类,并加载项目的上下文环境ApplicationContext

  9. 编写一个Controller

    package com.sheep.controller;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    @RequestMapping("/hello")
    public class HelloController {
    
        @GetMapping("/hello")
        @ResponseBody
        public String hello(){
            return "hello spring boot";
        }
    }
    
  10. 运行


application.yaml核心配置文件

概念

1、yaml文件格式是SpringBoot支持的一种JSON超文本格式,相对于传统的properties文件格式,yaml文件以数据为核心,是一种更为直观且容易被计算机识别的数据序列化格式,application.yaml和application.properties工作原理是一样的,只不过yaml格式的配置文件更加简洁。

2、xxx.yaml和xxx.properties是全局配置文件可以对SpringBoot一些默认配置只进行修改,在.yaml和.properties中可以对系统属性、环境变量、命令参数等信息进行更改配置,在springboot中推荐使用.yaml的格式进行配置。

语法

properties语法:key=value

yaml语法:key: value

  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进时不允许使用Tab键,只允许使用空格。
  • 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可

普通写法

name: sheep

对象写法

# 写法一
student1: {name: sheep,age: 3}
# 写法二
student2:
	name: sheep
	age: 3

数组写法

# 写法一
	# list
pets2: [cat,dog,pig]
	# map
pets2: {cat: 12,dog: 13,pig: 14}
# 写法二
	# list
pets1:
	- cat
	- dog
	# map
pets2:
	cat: 12
	dog: 13
	pig: 14

多文档模块

server:
  prot: 8080
---
server:
  prot: 8081
---
server:
  port: 8082

属性注入

1、使用@ConfigurationProperties(prefix = "")对属性注入值(SpringBoot自带注解)

  • yaml

    person:
      name: 梅西
      age: 33
      happy: true
      birth: 2000/08/12
      maps: {k1: v1,k2: v2}
      lists:
        - code
        - football
        - baesball
        - boxing
        - outdoor
      dog:
        name: 旺财
        age: 6
    
  • javaBean

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Component
    @ConfigurationProperties(prefix = "person")
    public class Person {
        private String name;
        private Integer age;
        private Boolean happy;
        private Date birth;
        private Map maps;
        private List lists;
        private Dog dog;
    }
    
    
    
    

    2、使用@Value()对属性赋值(Spring框架注解)

    • JavaBean

      @Data
      @AllArgsConstructor
      @NoArgsConstructor
      @Component
      public class Person {
          @Value("梅西")
          private String name;
          @Value("33")
          private Integer age;
          private Boolean happy;
          private Date birth;
          private Map maps;
          private List lists;
          private Dog dog;
      }
      
      
      
      

      3、两种注解对比

      • @ConfigurationProperties与@Value

        对比点 @ConfigurationProperties @Value
        底层框架 SpringBoot Spring
        功能 批量注入配置文件中的属性 单个注入
        setter方法 需要 不需要
        复杂类型属性注入 支持 不支持
        松散绑定 支持 不支持
        JSR303数据校验 支持 不支持
        SqEL表达式 不支持 支持

      松散绑定、SqEL表达式和JSR303数据校验

      • 松散绑定

        松散绑定是当注入的属性名与bean中的不一致是仍然可以实现属性赋值;使用@ConfigurationProperties注解配

        置文件时支持松散语法绑定;

        proson: {mName: 梅西}		//标准写法
        proson: {m-Name: 梅西}	//可以使用-线
        proson: {m_Name: 梅西}	//可以使用_线
        proson: {M_NAME: 梅西}	//可以使用大小写格式
        
      • SqEL表达式

        SqEL表达式即不使用配置文件的情况下直接使用@Value("#{5*2}"),直接对属性赋值

      • JSR303数据校验

        对前端传过来的数据进行校验

        yaml

        messi:
        	esail: 123e
        	age: 33
        

        javaBean

        @Data
        @AllArgsConstructor
        @NoArgsConstructor
        @Component
        @ConfigurationProperties(prefix = "messi")
        public class Messi{
            @Email(message="邮箱格式错误")
            private String email;
            @Value("33")
            private Integer age;
        }
        

        如果异常控制台将会显示打印异常

        JSR303数据校验详细:https://blog.csdn.net/weixin_44440642/article/details/106335653

      多环境配置

      1. 多个yaml文件配置和yaml的优先级

        • 当有多个.yaml或者.properties文件时可以使用@PropertySource(value = "")指定文件

          JavaBean

          @Data
          @AllArgsConstructor
          @NoArgsConstructor
          @Component
          @PropertySource(value = "classpath:sheep.yaml")//指定那个文件
          public class Person {
              private String name;
              private Integer age;
              private Boolean happy;
              private Date birth;
              private Map maps;
              private List lists;
              private Dog dog;
          }
          
          
          
        • 在SpringBoot项目中可以在多个位置定义.yaml配置文件;在不同位置指定的.yaml优先级都不一样

          上图对应的分别为:

          file:./config/:项目的config报下—优先级1

          file:./:项目文件下—优先级2

          classpath:/config/:类路径config报下—优先级3

          classpath:/:类路径下—优先级4

        • yaml多个运行环境配置

          当应用程序需要部署到不同的运行环境中时,比如:开发环境、测试环境、生产环境,可以使用不同的properties文件配置。

          • properties方式

            在配置多个环境时为.yaml取名必须要求取名比如:application-{prifile}.yaml

            application-dev.properties		# 开发环境配置
            application-test.properties		# 测试环境配置
            application-prod.properties 	# 生产环境配置
            

            使用相应的环境时在全局配置文件中开启

            spring.profiles.action=dev
            
          • yaml方式

            server:
              port: 8080
            spring:
              profiles:
                active: test	# 开启test环境,如果不使用默认8080
            ---
            server:
              port: 8081
            spring:
              profiles: dev
            ---
            server:
              port: 8082
            spring:
              profiles: test
            
        • 随机值设置和参数间引用

          • 随机值设置:${random.xxx},xxx表示指定生成随机数的范围和类型

            person:
              name: 梅西${random.uuid}	 # 随机生成UUID类型数 
              age: ${random.int}		  # 随机生成int类型数
              happy: true
              birth: 2000/08/12
              maps: {k1: v1,k2: v2}
              lists:
                - code
                - football
                - baesball
                - boxing
                - outdoor
              dog:
                name: 旺财
                age: 6
            

            常用随机数

            ${random.value}					# 随机字符串
            ${random.int}					# 随机整数
            ${random.long}					# 随机long类型数
            ${random.uuid}					# 随机UUID类型数
            ${random.int(10)}				# 小于10的随机整数
            ${random.int[1024,2000]}		# 在[1024,2000]之间的随机整数
            
          • 参数间引用:顾名思义先配置的参数可以在后配置的参数中使用

            person:
              name: 梅西${random.uuid}	   # 随机生成UUID类型数 
              age: ${random.int}            # 随机生成int类型数
              happy: true
              birth: 2000/08/12
              maps: {k1: v1,k2: v2}
              hello: happy
              lists:
                - code
                - football
                - baesball
                - boxing
                - outdoor
              dog:
                name: ${person.hello:hello}_旺财 # 参数间引用如果hello参数存在则happy__旺财,否则hello_参数
                age: 6