SpringBoot学习笔记

2019年7月23日

1.Spring Boot简介

  简化Spring应用开发的一个框架

  整个Spring技术栈的整合

  J2EE开发的一站式解决方案

2.微服务

  微服务:架构风格

  一个应用应该是一组小型服务;可以通过HTTP方式进行互通

  每一个功能元素最终都是一个可独立替换和独立升级的软件单元

3.配置文件

  作用:修改SpringBoot自动配置的默认值

  application.properties

  application.yml

  (1)yaml基本语法

    k: v:表示一对键值对(空格必须有)

    以空格的缩进来控制层级关系

    属性和值大小写敏感 

  (2)值得写法

    字面量:普通的值(数字,字符串,布尔)

      k: v:字面直接来写

        字符串默认不用加上单引号或者双引号

        "":双引号不会转义字符串里面的特殊字符,特殊字符会作为本身想表示的意思

        '':单引号会转义特殊字符,特殊字符最终只是一个普通的字符串数据

    对象、Map(属性和值)(键值对)

      k: v:在下一行来写对象的属性和值的关系

        对象还是k: v的方式

        friends:

          lastName:zhangsan

          age:20

        行内写法:

        friends: {lastName: zhangsan,age: 18}

    数组(List、Set)

      用- 值表示数组中的一个元素

        pets:

         - cat

         - dog

         - pig

      行内写法

        pets: [cat,dog,pig]

  (3)配置文件值注入

配置文件:application.yml

server:
    port: 8081

person:
    lastName: zhangsan
    age: 18
    boss: false
    birth: 2017/12/12
    maps: {k1: v1,k2: 12}
    lists: [lisi,zhaoliu]
    dog: {name: 小狗,age: 12}

配置文件:application.properties

person.last-name=张三
person.age=18
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=dog
person.dog.age=15

javaBean:

/**
 * 将配置文件中每一个属性的值,映射到这个组件中
 * @ConfigurationProperties:告诉SpringBoot将本类中所有属性和配置文件中相关的配置进行绑定
 *      prefix = "person":配置文件中哪个下面的所有属性进行一一映射
 * 只有这个组件是容器中的组件,才能使用容器提供的@ConfigurationProperties功能
* @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值
*/ @Component @ConfigurationProperties(prefix = "person") public class Person { private String lastName; private Integer age; private Boolean boss; private Date birth; private Map<String,Object> maps; private List<Object> lists; private Dog dog;

导入配置文件处理器

<!--导入配置文件处理器,配置文件进行绑定会有提示-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

@ConfigurationProperties获取配置文件值

@Component
@ConfigurationProperties(prefix = "person")

@Value获取文件值

public class Person {
    
    @Value("${person.last-name}")
    private String lastName;
    @Value("#{11*2}")
    private Integer age;
    @Value("true")
    private Boolean boss;
    private Date birth;

  (4)@PropertySource&@ImportResource

  @PropertySource:加载指定的配置文件

@PropertySource(value = {"classpath:***.properties"})
@Component
@ConfigurationProperties(prefix = "person")
public class Person {

    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;

  @ImportResource:导入Spring的配置文件,让配置文件里面的内容生效

  Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别

@ImportResource({"classpath:***.xml"})

  (5)Spring推荐使用@Bean给容器添加组件

/**
 * @Configuration:指明当前类是一个配置类,用来替代Spring配置文件
 */
@Configuration
public class MyAppConfig {

    //将方法的返回值添加到容器中:容器中这个组件默认的id就是方法名
    @Bean
    public HelloService helloService(){
        return  new HelloService();
    }
}

 2019年7月24日

1.配置文件占位符

  (1)随机数

${random.value}、${random.int}、${random.long}
${random.int(10)}、${random.int[1024,65536]}

  (2)占位符获取之前配置的值,如果没有可以用:指定默认值

person.last-name=张三${random.uuid}
person.age=${random.int}
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=${person.last-name:name}_dog
person.dog.age=15

2.Profile

Profile是Spring对不同环境提供不同配置功能的支持,可以通过激活、指定参数等方式快速切换环境

  (1)多Profile文件

    编写主配置文件时,文件名可以是application-{profile}.properties/yml

    默认使用application.properties的配置

  (2)yml支持多文档方式

server:
    port: 8081
spring:
    profiles:
        active: prod

---
server:
    port: 8083
spring:
    profiles:dev

---
server:
    port: 8084
spring:
    profiles:prod

  (3)激活指定profile

  • 在配置文件中指定spring.profile.active=***
  • Run/Debug Configurations-->Program arguments:--spring.profiles.active=***
  • 打包后通过命令行的方式运行:java -jar ***.jar --spring.profiles.active=***
  • 虚拟机参数:Run/Debug Configurations-->VM options:--Dspring.profiles.active=***

 3.配置文件加载位置

Spring Boot启动会扫描以下位置的application.properties或者application.yml文件作为Spring Boot的默认配置文件

  • file:./config/
  • file:./
  • classpath:/config
  • classpath:/

以上按照优先级从高到低的顺序,所有位置的文件都会被加载,高优先级配置内容会覆盖低优先级配置内容

还可以通过spring.config.location来改变默认的配置文件的位置

项目打包好以后,我们可以使用命令行参数的形式,启动项目的时候来指定配置文件的新位置;指定配置文件和默认加载的配置文件共同起作用形成配置互补

4.外部配置加载顺序

SpringBoot也可以从以下位置加载配置;优先级从高到低;高优先级的配置覆盖低优先级的配置,所有的配置会形成互补配置

  • 命令行参数

    java -jar ***.jar -server.port=**** -server.context.path=/***

  • 来自java:comp/env的NDI属性
  • java系统属性(System.getProperties())
  • 操作系统环境变量
  • RandomValuePropertySource配置的random.*属性
  • jar包外部的application-{profile}.properties/yml配置文件
  • jar包内部的application-{profile}.properties/yml配置文件
  • jar包外部的application.properties/yml配置文件
  • jar包内部的application.properties/yml配置文件
  • @Configuration注解类上的@PropertySource
  • 通过SpringApplication.setDefaultProperties指定的默认属性

5.自动配置原理

  (1)SpringBoot启动的时候加载主配置类,开启了自动配置功能@EnableAutoConfiguration

  (2)@EnableAutoConfiguration作用:

  • 利用EnableAutoConfigurationImportSelector给容器中导入一些组件
  • List<String> configurations = getCandidateConfigurations(annotationMetadata,attribute);获取候选配置
SpringFactoriesLoader.loadFactoryNames()
扫描所有jar包类路径下    META-INF/spring.factories
把扫描到的这些文件内容包装成properties对象
从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后填入到容器中

  (3)每一个自动配置类进行自动配置功能

    ex:HttpEncodingAutoConfiguration

@Configuration    //表示这是一个配置类,可以给容器添加组件
@EnableConfigurationProperties(HttpEncodingProperties.class)    //启用指定类的ConfigurationProperties功能:将配置文件中对应的值和HttpEncodingProperties绑定起来
@ConditionalOnWebApplication    //判断当前应用是否是web应用;Spring底层@Condition注解,如果满足指定的条件,整个配置类才会生效
@ConditionalOnClass(CharacterEncodingFilter.class)   // 判断当前项目有没有这个类
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enable", matchIfMissing = true)    //判断配置文件中是否存在某个配置;如果不存在,也是成立的
public class HttpEncodingAutoConfiguration {

根据当前不同的条件判断,决定这个配置类是否生效;一但这个配置类生效,这个配置类就会给容器中添加各种组件;这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又和配置文件绑定

  (4)总结

  • SpringBoot启动会加载大量的自动配置类
  • 我们需要的功能有没有SpringBoot默认写好的自动配置类
  • 自动配置类包含哪些组件
  • 给自动配置类添加组件的时候,会从properties类中获取某些属性。我们可以在配置文件中指定这些属性的值

6.SpringBoot日志

SpringBoot选用SLF4j和logback实现记录日志

  (1)SLF4j

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld {
  public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger(HelloWorld.class);
    logger.info("Hello World");
  }
}

  (2)如何让系统中所有的日志都统一到slf4j:

    将系统中其他日志框架先排除

    用中间包来替换原有的日志框架

    导入slf4j其他的实现

  (3)日志使用

    SpringBoot默认帮助我们配置好了日志

#日志输出级别设置
logging.level.com.mxj=trace

#不指定路径在当前项目下生成springboot.log日志
#可以指定完整的路径
logging.file=D:/***.log

#在当前磁盘的根路径下创建spring文件夹和里面的log文件夹:使用spring.log作为默认文件
logging.path=/spring/log

#在控制台输出的日志格式
logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n
#指定文件中日志输出的格式
logging.pattern.file=%d{yyyy-MM-dd} === [%thread] === %-5level === %logger{50} === %msg%n
日志输出格式:
    %d:表示日期时间
    %thread:表示线程名
    %-5level:从左显示5个字符宽度
    %logger{50}:表示logger名字最长50个字符,否则按照句点分割
    %msg:日志消息
    %n:换行符

   (4)切换日志框架

  可以按照slf4j的日志适配图,进行相关的切换

7.SpringBoot_Web开发

  (1)使用SpringBoot

  • 创建SpringBoot应用,选中我们需要的模块
  • SpringBoot已经将场景配置好,只需少量配置就可以运行
  • 编写业务代码

  (2)自动配置原理

****AutoConfiguration:给容器自动配置组件
****Properties:配置类封装配置文件的内容

   (3)SpringBoot对静态资源的映射规则

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware, InitializingBean {
  //可以设置和静态资源有关的参数,缓存时间
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
                return;
            }
            Integer cachePeriod = this.resourceProperties.getCachePeriod();
            if (!registry.hasMappingForPattern("/webjars/**")) {
                customizeResourceHandlerRegistration(registry
                        .addResourceHandler("/webjars/**")
                        .addResourceLocations("classpath:/META-INF/resources/webjars/")
                        .setCachePeriod(cachePeriod));
            }
            String staticPathPattern = this.mvcProperties.getStaticPathPattern();
            if (!registry.hasMappingForPattern(staticPathPattern)) {
                customizeResourceHandlerRegistration(
                        registry.addResourceHandler(staticPathPattern)
                                .addResourceLocations(
                                        this.resourceProperties.getStaticLocations())
                                .setCachePeriod(cachePeriod));
            }
        }
  • 所有/webjars/**,都去classpath:/META-INF/resources/webjars/找资源

    webjars:以jar包的方式引入静态资源

<!--引入jquery-webjar-->在访问时只需写webjars下面资源的名字
        <dependency>
            <groupId>org.webjars.bower</groupId>
            <artifactId>jquery</artifactId>
            <version>3.4.1</version>
        </dependency>
  • "/**"访问当前项目的任何资源(静态资源的文件夹)
"classpath:/META-INF/resources/"
"classpath:/resources/"
"classpath:static/"
"classpath:/public/"
"/"当前项目的根路径
  • 欢迎页:静态资源文件夹下的所有index.html页面:被“/**”映射

    localhost:8080/ 找index页面

  • 所有的**/favicon.ico都是在静态资源文件下找

   (3)模板引擎——Thymeleaf

引入Thymeleaf

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--切换thymeleaf版本-->
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<!--布局功能支持程序-->
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>

Thymeleaf使用&语法

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

    private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");

    private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");

    public static final String DEFAULT_PREFIX = "classpath:/templates/";

    public static final String DEFAULT_SUFFIX = ".html";

//只要我们把HTML页面放在classpath:/templates/文件夹下,thymeleaf就能自动渲染

使用:

  • 导入thymeleaf的名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
  • 使用thymeleaf语法
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--th:text 设置div里面的文本内容-->
    <div th:text="${hello}">这里显示欢迎信息</div>
</body>
</html>
  • 语法规则

  (1)th : 任意html属性,来替换原声属性的值

    片段包含:th:insert th:replace

    遍历: th:each

    条件判断:th:if th:unless th:switch th:case

    声明变量:th:object th:with

    任意属性修改:th:attr th:attrprepend th:attrappend

    修改指定属性默认值:th:value th:href th:src

    修改标签体内容:th:text(转义特殊字符) th:utext(不转义特殊字符)

    声明片段:th:fragment th:remove

  (2)表达式语法

    ${...}:获取变量值OGNL

      获取对象的属性、调用方法

      使用内置的基本对象:ctx vars locale request response session servletContext

    *{...}:和${...}在功能上是一样的,配合th:object使用

    #{...}:获取国际化内容

    @{...}:定义URL

    ~{...}:片段引用表达式

  (3)内置的工具对象

example:

@Controller
public class HelloController {
    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        return "Hello World";
    }

    @RequestMapping("/success")
    public String success(Map<String,Object> map){
        map.put("hello","<h1>你好</h1>");
        map.put("users", Arrays.asList("zhangsan","lisi","wangwu"));
        return "success";
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--th:text 设置div里面的文本内容-->
<div th:text="${hello}">这里显示欢迎信息</div>

<div th:text="${hello}"></div>
<div th:utext="${hello}"></div>
<hr/>

<!-- th:each每次遍历都会生成当前标签,3个h4-->
<h4 th:text="${user}" th:each="user:${users}"></h4>
<hr/>
<h4>
    <span th:text="${user}" th:each="user:${users}"></span>
</h4>
</body>
</html>

8.SpringBoot-SpringMVC自动配置

SpringBoot自动配置好了SpringMVC:

  • 自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染(转发?重定向?)

    ContentNegotiatingViewResolver:组合所有的视图解析器

      如何定制:我们可以自己给容器中添加一个视图解析器,自动将其组合进来

  • 静态资源文件夹路径
  • 静态首页访问
  • 自动注册Converter,GenericConverter,Formatter beans

    Converter:类型转换器

    Formatter:格式化器

  • HttpMessageConverters:SpringMVC用来转换Http请求和相应 User--json
  • 定义错误代码生成规则
posted @ 2019-07-23 16:37  M_x_j  阅读(244)  评论(0编辑  收藏  举报