• SpringBoot详解配置文件


    上篇简单了解了SpringBoot的概念并学会如何搭建一个SpringBoot项目,今天就来学习SpringBoot的配置文件的种类与用法

    前景引入

    在学习SpringBoot之前,SSM项目的配置复杂程度堪称配置地狱,一开始开发者就对Spring、SpringMVC、Mybatis、tomcat进行配置,这浪费了我们大量的时间去构建项目,而且如果配置一旦出现错误,项目就有可能崩溃。

    SpringBoot采用了自动配置,以前需要配置的东西,Spring Boot帮我们自动配置,使得开发者更加关注于业务代码的开发

    什么是SpringBoot自动配置?

    • 指的是基于你引入依赖的jar包,对SpringBoot应用自动配置

    • 它为SpingBoot框架“开箱即用”提供了基础支撑

    使用过SpringBoot的都知道启动类中使用了@SpringBootApplicatin注解,打开源码我们查看一下元注解

    1. @Target({ElementType.TYPE})
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Documented
    4. @Inherited
    5. @SpringBootConfiguration
    6. @EnableAutoConfiguration
    7. @ComponentScan(
    8.     excludeFilters = {@Filter(
    9.     type = FilterType.CUSTOM,
    10.     classes = {TypeExcludeFilter.class}
    11. ), @Filter(
    12.     type = FilterType.CUSTOM,
    13.     classes = {AutoConfigurationExcludeFilter.class}
    14. )}
    15. )
    16. public @interface SpringBootApplication {
    17.     @AliasFor(
    18.         annotation = EnableAutoConfiguration.class
    19.     )
    20.     Class[] exclude() default {};
    21.     @AliasFor(
    22.         annotation = EnableAutoConfiguration.class
    23.     )
    24.     String[] excludeName() default {};
    25.     @AliasFor(
    26.         annotation = ComponentScan.class,
    27.         attribute = "basePackages"
    28.     )
    29.     String[] scanBasePackages() default {};
    30.     @AliasFor(
    31.         annotation = ComponentScan.class,
    32.         attribute = "basePackageClasses"
    33.     )
    34.     Class[] scanBasePackageClasses() default {};
    35.     @AliasFor(
    36.         annotation = ComponentScan.class,
    37.         attribute = "nameGenerator"
    38.     )
    39.     Classextends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;
    40.     @AliasFor(
    41.         annotation = Configuration.class
    42.     )
    43.     boolean proxyBeanMethods() default true;
    44. }

    我们主要关注三个元注解,分别为@SpringBootConfiguration、@E nableAutoConfiguration、@ComponentScan
    1、@SpringBootApplication修饰的类,也会被@Configuration间接修饰,即“源配置类”

    2、SpringBoot框架会对“源配置类”所在的package进行组件扫描

    3、SpringBoot框架最终会导入AutoConfigurationImportSelector来实现自动配置

    配置文件分类

    • SpringBoot提供了两种能被识别的配置文件,分别为properties和yaml/yml文件

    • 在同一级目录下优先级为:properties > yml > yaml

    • 默认配置文件名称:application

    yml/yaml文件类型

    概念: YML文件格式是YAML (YAML Aint Markup Language)编写的文件格式,YAML是一种直观的能够被电脑识别的的数据数据序列化格 式,并且容易被人类阅读,也容易和脚本语言交互

    语法与特点:

    • 大小写铭感

    • 数据值前边必须有空格,作为分隔符

    • 使用缩进表示层级关系

    • 缩进时不允许使用Tab键,只允许使用空格(各个系统Tab对应的空格数目可能不同,导致层次混乱)

    • 缩进的空格数目不重要,只要相同级的元素左侧对齐即可

    示例:以定义服务器端口和主机为例

    1. server
    2.   port: 8080
    3.   address: 127.0.0.1

    数据类型定义

    对象(map)

    1. person:
    2.  name: zhangsan
    3. #行内写法
    4. person: {name: zhangsan}

    数组(array)

    1. address:
    2.  - beijing
    3.  - shangsai
    4. # 行内写法
    5. address: {beijing,shanghai}

    常量

    1. msg1: 'hello \n world'   #单引忽略转义字符
    2. msg2: "hello \n world"  #双引识别转义字符

    同类比较

    下面我们将yml与properties和xml文件格式进行比较

    • xml

    1. <server>
    2.   <port>8080port>
    3.   <address>127.0.0.1address>  
    4. server>
    • properties

    1. server.port=8080
    2. server.address=127.0.0.1
    • yml

    1. server
    2.   port: 8080
    3.   address: 127.0.0.1

    区别:
    1、xml文件主要是树形结构,xml配置文件结构清晰,但是内容比较繁琐
    2、properties文件主要是以key-value键值对的形式存在,文件结构简单,但难以表达层次
    3、yml文件不是一种标记语言,但容易表现层级关系,而且语法简洁精炼

    获取配置文件数据

    SpringBoot提供了以下三个注解来获取配置文件数据
    @Value
    @Environment
    @ConfigurationProperties

    • 第一种方式,使用@Value yml文件

    1.   user1:
    2.     name: zhangsan

    1、Controller层,获取对象数据(user1.name)

    1.   @Controller
    2.   public class HelloController {
    3.       @Value("${user1.name}")
    4.       private String name;
    5.   
    6.       @ResponseBody
    7.       @RequestMapping("/param")
    8.       public String hello(){
    9.           System.out.println(name);
    10.           return "param";
    11.       }
    12.   
    13.   }

    2、获取数组数据
    yml文件:

    country: [China,Italy]
    

    Controller测试

    1. @Controller
    2. public class HelloController {
    3.     @Value("${user1.name}")
    4.     private String name;
    5.     @Value("${country[0]}")
    6.     private String country1;
    7.     @ResponseBody
    8.     @RequestMapping("/param")
    9.     public String hello(){
    10.         System.out.println("country1 : "+country1);
    11.         return "param";
    12.     }
    13. }
    • 第二种方式,使用Environment对象获取数据,这个方法比较方便

      在Controller层,创建Environment对象,并自动注入,然后使用对象的getProperty方法获取数据

    1.   @RestController
    2.   public class Test1Controller {
    3.       @Autowired
    4.       Environment env;
    5.   
    6.       @RequestMapping("/test1")
    7.       public String test1(){
    8.           System.out.println("country[0] : "+env.getProperty("country[0]"));
    9.           System.out.println("user1.name : " + env.getProperty("user1.name"));
    10.           return "test1";
    11.       }
    12.   }

    输出如下:

    1.   country[0] : China
    2.   user1.name : zhangsan
    • 方式三:使用@ConfigurationProperties获取数据

      首先创建一个Bean,加上@ConfigurationProperties注解,还有一定要加上prefix前缀

      注意:Bean成员一定要跟yml的数据一一对应

    1. @Component
    2. @ConfigurationProperties(prefix = "admin")
    3. public class Admin {
    4.     private String userName;
    5.     private String password;
    6.     private String[] hobby;
    7.     public String getUserName() {
    8.         return userName;
    9.     }
    10.     public void setUserName(String userName) {
    11.         this.userName = userName;
    12.     }
    13.     public String getPassword() {
    14.         return password;
    15.     }
    16.     public void setPassword(String password) {
    17.         this.password=password;
    18.     }
    19.     public String[] getHobby() {
    20.         return hobby;
    21.     }
    22.     public void setHobby(String[] hobby) {
    23.         this.hobby = hobby;
    24.     }
    25.     @Override
    26.     public String toString() {
    27.         return "Admin{" +
    28.                 "userName='" + userName + '\'' +
    29.                 ", password='" + password + '\'' +
    30.                 ", hobby=" + Arrays.toString(hobby) +
    31.                 '}';
    32.     }
    33. }

    然后在Controller层,创建一个Admin对象,并自动注入

    1. @RestController
    2. public class Test1Controller {
    3.     @Autowired
    4.     private Admin admin;
    5.     @RequestMapping("/test2")
    6.     public String test2(){
    7.         System.out.println("userName: "+admin.getUserName());
    8.         System.out.println("password: "+admin.getPassword());
    9.         for (String hobby : admin.getHobby()) {
    10.             System.out.println(hobby);
    11.         }
    12.         return "test2";
    13.     }
    14. }

    输出:

    1. userName: admin
    2. password: 123
    3. music
    4. play game

    至此,本篇内容结束,如果你喜欢本篇,欢迎点赞+关注,前方不迷路,祝各位生活愉快!

  • 相关阅读:
    TCP与应用层协议
    8-4交换排序-冒泡排序
    【JavaSe笔记】——类和对象、this引用、构造方法、封装、static、代码块
    Flutter快学快用07 状态管理:Flutter 状态管理及对比选型
    cocos-lua定时器用法
    linux实战项目经验得到的常用linux命令(2) 磁盘分区和内容查找
    连续10年霸榜第一?程序员「最常用」的编程语言是它?
    100天精通Python(爬虫篇)——第45天:lxml库与Xpath提取网页数据
    2022年,都在说软件测试饱和了,大环境不好?为何每年还会增加40万测试员?
    HTML实现猜数字游戏
  • 原文地址:https://blog.csdn.net/calm_programmer/article/details/126119968