SpringBoot 基础01

SpringBoot 基础

pom.xml

<!-- Spring Boot 依赖版本控制 -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<!-- 
spring-boot-start-web:
spring-boot-start: spring-boot场景启动器;导入web模块所需的依赖
-->

主程序类,入口类

  • @SpringBootApplication 标注入口类,SpringBoot从这里的main方法启动;

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    @SpringBootConfiguration
    @EnableAutoConfiguration
    @ComponentScan(
        excludeFilters = {@Filter(
        type = FilterType.CUSTOM,
        classes = {TypeExcludeFilter.class}
    ), @Filter(
        type = FilterType.CUSTOM,
        classes = {AutoConfigurationExcludeFilter.class}
    )}
    )
    public @interface SpringBootApplication { ...}
    
    @AutoConfigurationPackage
    @Import({AutoConfigurationImportSelector.class})
    public @interface EnableAutoConfiguration {
    
    • @SpringBootConfiguration:Spring Boot的配置类
      • @Configuration:标注在配置类上; 配置类 ---- 配置文件
    • @EnableAutoConfiguration:开启自动配置
      • @AutoConfigurationPackage:自动配置包
      • @Import({xxxx.class}):底层注解,给容器自动导入一个组件

resource文件夹

  • static: 静态资源
  • templates: 模板页面(Spring Boot默认使用嵌入式的Tomcat,默认不支持JSP;可以使用模板引擎)
  • application.properties: Spring Boot配置文件
    • @PropertySource(value = {"classpath:config.properties"}):指定配置文件
    • SpringBoot默认使用的全局配置文件:
      • application.properties
      • application.yml

配置文件

  • YAML 语法

    • k:(空格)v: 一对键值对,属性、值大小敏感
    • 以空格缩进表示层级关系
      # 字面量:普通的值
      # 双引号:不会转义特殊字符;单引号:会转义特殊字符
      # 对象、Map:在下一行写对象的属性和值的关系,注意缩进
      # 数组:用`-`来表示数组中的一个元素
      k: v
      friend1:
          name: zhangsan
          age: 20
      friend2: {name: lisi, age: 18}  # 行类写法
      pets1:
          - cat
          - dog
      pets2: [cat, dog]
      
  • 导入配置文件处理器

    <!--导入配置文件处理器,配置文件进行绑定就会有提示-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    
  • 配置信息封装成实体类

    • @Component:组件类,自动加载到容器
    • @ConfiguartionProperties(prefix = "xxx"):将类中的属性与配置文件进行绑定;prefix="xxx":配置文件下的哪个对象进行映射
    • @Value:指定属性注入,不支持松散语法绑定
原文地址:https://www.cnblogs.com/ppos/p/10057898.html