SpringBoot学习记录(一)

一.SpringBoot入门

1.SpringBoot简介

简化Spring应用开发的一个框架;整个Spring技术栈的一个大整合;J2EE开发的一站式解决方案;

SpringBoot的优点:

(1) 快速创建独立运行的Spring项目以及主流框架集成

(2) 使用嵌入式的Servlet容器,应用无需打成war包

(3) starters自动依赖与版本控制

(4) 大量的自动配置,简化开发,也可修改默认值

(5) 无需配置xml,无代码生成,开箱即用

(6) 准生成环境的运行时应用监控

(7) 与云计算的天然集成


缺点:SpringBoot入门容易,精通难;如果不对spring框架的原理了解,那么对springboot的开发原理也有一定的难度。

2.微服务

架构风格(服务微化)

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

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

3.springboot入门程序helloworld

完成功能:浏览器发送hello请求,服务器接收请求并处理,响应Hello World

具体步骤:

(1) 创建maven工程;(jar)

(2) 导入依赖spring boot相关的依赖

根据官方文档,导入依赖

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring‐boot‐starter‐parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring‐boot‐starter‐web</artifactId>
        </dependency>
    </dependencies>

 (3) 编写主程序,启动springboot应用

/**
 * @SpringBootApplication 来标注一个主程序,说明这是一个Spring boot应用
 */
@SpringBootApplication
public class SpringBoot01Application {

    public static void main(String[] args) {
        //Spring应用启动起来
        SpringApplication.run(SpringBoot01Application.class, args);
    }
}

(4) 编写相关的Controller,Service

/**
 * @program: spring-boot-01
 * @description: Spring boot HelloWorld
 * @author: Yukai Fan
 * @create: 2018-10-16 20:22
 **/
@Controller
public class HelloController {

    @RequestMapping("/hello")
    @ResponseBody
    public String hello() {
        return "hello world!";
    }
}

第二种方式:

//这个注解就是@controller与@ResponseBody的合体
@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello() {
        return "hello world!";
    }
}

 

(5) 运行主程序测试

(6) 简化部署

在pom文件中导入依赖

    <!-- 这个插件,可以将应用打包成一个可执行的jar包 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

只需要将这个应用打成jar包,直接使用java -jar的命令进行执行即可,不需要tomcat。因为springboot的jar包已经依赖了tomcat所需要的jar包。

4.探究Hello World程序

(1)

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring‐boot‐starter‐parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>

他的父项目是
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring‐boot‐dependencies</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath>../../spring‐boot‐dependencies</relativePath>
</parent>
这个是真正管理Spring boot应用里面的所有依赖的版本

Spring Boot的dependencies是版本仲裁中心;

以后我们导入依赖默认是不需要写版本;(没有在dependencies里面管理的依赖需要声明版本号)

(2) 还有一个spring-boot-starter-web;启动器依赖:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

spring-boot-starter:spring-boot场景启动器;帮我导入了web磨矿正常运行所依赖 的组件;

Spring Boot将所有的功能场景都抽取出来,做成一个个starters(启动器),只需要在项目里面引入相关场景的所有依赖都会导入进来。要用什么功能酒倒入什么场景的启动器。

(3) 主程序类,主入口类

/**
 * @SpringBootApplication 来标注一个主程序,说明这是一个Spring boot应用
 */
@SpringBootApplication
public class SpringBoot01Application {

    public static void main(String[] args) {
        //Spring应用启动起来
        SpringApplication.run(SpringBoot01Application.class, args);
    }
}

@SpringBootApplication:Spring Boot应用标注在某个类上说明这个类是SpringBoot的主配置类,SpringBoot就应该运行这个类的main方法来启东SpringBoot应用;

@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 {

@SpringBootConfiguration:SpringBoot的主配置类;标注在某个类上,表示这是一个SpringBoot的配置类

@Configuration:配置类上来标注这个注解;

  配置类-------配置文件;配置类也是容器中的一个组件;@Componment

@EnableAutoConfiguration:开启自动配置功能;以前我们需要配置的东西,SpringBoot帮我们自动配置

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {

@AutoConfigurationPackage:自动配置包,主要的作用是讲主配置类(@SpringBootConfiguration标注的类)的所在包以及下面所有子包里面的所有组件扫描到Spring容器;

(所以如果将controller类写在主配置类包的外面,那么就无法访问controller请求)

  @Import(AutoConfigurationPackages.Registrar.class);

  Spring的底层注解@Import,给容器中导入一个组件;导入的组件有AutoConfigurationPackages.Registrar.class;

@Import(AutoConfigurationImportSelector.class):给容器导入组件

  AutoConfigurationImportSelector:导入哪些组件的选择器,将所有需要导入的组件以全类名 的方式返回;这些组件就会被添加到容器中,会给容器中导入非常多的自动配置类(xxxAutoConfiguration);就是给容器中导入这个场景所需要的所有组件,并配置好这些组件;有了自动配置类,免去了我们手动编写配置注入功能组件等工作。

SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, classLoader) 

SpringBoot在启动的时候从类路径下的META-INF/spring.factories中获取EnableAutoConfiguration指定的值,将这些值作为自动配置类导入到容器中,自动配置类就生效,帮我进行自动配置工作。

 

根据上面的讲解可知,为什么SpringBoot简单,不需要繁琐的配置,完全由SpringBoot自动配置和解决方案?

全都在这个jar包中spring-boot-autoconfigure-1.5.9.RELEASE.jar;

二.使用Spring Initializer快速创建SpringBoot项目

IDE都支持Spring得项目创建向导快速创建一个SpringBoot项目;选择我们需要的模块,向导会联网创建SpringBoot项目;

默认生成的SpringBoot项目;

  (1) 主程序已经生成好,我们只需要编写业务逻辑

  (2) resources文件夹中目录结构

    

    static:保存所有的静态资源;js css images

    templates:保存所有的模板页面;(Spring Boot默认jar包使用嵌入式的tomcat,默认不使用jsp,可以使用模板引擎freeworker,thymeleaf)

    application.properties:SpringBoot应用的配置文件,可以修改一些默认配置;

三.配置文件

SpringBoot 使用一个全局配置文件,配置文件吗是固定的的;

  application.properties  

  application.yml

配置文件的作用:修改SpringBoot自动配置的默认值;SpringBoot在底层都自动配置好

YAML(YAML Ain't Markup Language)

  YAML Ain't Markup Language:YAML不是一个标记语言

  YAML:以数据为中心,比json,xml等更合适做配置文件;

标记语言:

  以前的配置文件大多使用xml文件

1.YAML语法

  (1) 基本语法

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

    以空格的缩进老控制层级关系;只要左对齐的一列数据,都是同一个层级的,属性和值是大小写敏感的

server:
    port:8081
    path:/hello

2.值的写法

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

   k:v:字面直接来写;

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

      “”:双引号不会转义字符串里面的特殊字符;特殊字符串回座位本身想表示的意思

        name:"zhangsan \n lisi" 输出 zhangsan 换行 lisi

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

        name:'zhangsan \n lisi' 输出 zhangsan \n lisi

 

3.对象,Map(属性和值)(键值对)

  k:v:在下一行来写对象的属性和值的关系;注意缩进

     对象还是k:v的形式

friends:
    lastname: zhangsan
    age: 20

4.数组(List,Set)

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

pets:
    - cat
    - dog
    - pig

行类写法

pets: [cat,dog,pig]

 

4.配置文件值注入

Yaml配置文件:

person:
    lastName: zhangsan
    age: 18
    boss: false
    birth: 2018/10/17
    maps: {k1: v1,k2: 12}
    lists:
      - lisi
      - wangwu
    dog:
      name: xiaogou
      age: 2

JavaBean实例:

/**
 * @program: spring-boot-01
 * @description:
 *  将yaml配置文件中的每一个属性值,映射到这个组件中
 *  @ConfigurationProperties:告诉SpringBoot将本类的所有属性和配置文件中相关的配置进行绑定;默认从全局配置文件中获取值
 *      prefix = "person":配置文件中哪个下面的所有属性进行一一映射
 *  只有这个组件是容器中的组件,容器才能提供@ConfigurationProperties功能,所以需要加上@Compoent注解
 * @author: Yukai Fan
 * @create: 2018-10-17 20:23
 **/
@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;

    @Override
    public String toString() {
        return "Person{" +
                "lastName='" + lastName + '\'' +
                ", age=" + age +
                ", boss=" + boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", lists=" + lists +
                ", dog=" + dog +
                '}';
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Boolean getBoss() {
        return boss;
    }

    public void setBoss(Boolean boss) {
        this.boss = boss;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Map<String, Object> getMaps() {
        return maps;
    }

    public void setMaps(Map<String, Object> maps) {
        this.maps = maps;
    }

    public List<Object> getLists() {
        return lists;
    }

    public void setLists(List<Object> lists) {
        this.lists = lists;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }
}
/**
 * @program: spring-boot-01
 * @description: dog
 * @author: Yukai Fan
 * @create: 2018-10-17 20:26
 **/
public class Dog {

    private String name;
    private Integer age;

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

导入的依赖:

<!-- 导入配置处理器,配置文件进行绑定就会有提示 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring‐boot‐configuration‐processor</artifactId>
            <optional>true</optional>
        </dependency>
区别@ConfigurationProperties@Value
功能 批量注入配置文件中的属性 一个一个指定
松散绑定 支持(即可以用last-name代替lastName) 不支持(不能用last-name)
SpEL 不支持(不能写表达式#{11*2}) 支持(可以使用表达式计算#{11*2})
JSR303数据校验 支持 不支持
复杂类型封装 支持 不支持(Map,List,Set)

配置文件yml还是properties都能获取到值;

如果我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,就是用@Value

如果我们专门编写一个javabean来和配置文件进行映射,我们就直接使用@ConfigurationProperties

5.配置文件注入值数据校验

@Component
@ConfigurationProperties(prefix = "person")
public class Person {

    /**
     * <bean class="Person">
     *      <property name="lastName" value="字面值/${key}从环境变量,配置文件中获取值/#{SpEl}"></property>
     * </bean>
     */
    //@Value("${person.last-name}")
    //lastName必须是邮箱格式
    @Email
    @Value("${person.last-name}")

6.加载指定的配置文件

@PropertySource(value = {"classpath: 配置文件名"})

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

person.properties:

person.last-name=张三
person.birth=2018/10/17
person.boos=false
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=dog
person.dog.age=2

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

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

想让Spring配置文件加载进来,就需要@ImportResource标志在主配置类上

 

SpringBoot推荐给容器中添加组件的方式:

推荐使用全注解的方式

1.配置类@Configuration----->Spring配置文件

2.使用@Bean给容器添加组件

//将方法的返回值添加到容器中,容器中这个组件默认的id就是方法名
    @Bean
    public HelloService helloService() {
        System.out.println("配置类@Bean给容器中添加组件了。。。");
        return new HelloService();
    }

7.配置文件占位符

(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=2018/10/17
person.boos=false
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog
person.dog.age=2

8. Profile

(1) 多Profile文件

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

默认使用application.properties的配置;

(2) yml支持多文档块方式

server:
  port: 8081
spring:
  profiles:
    active: prod #profiles.active:激活指定配置
---

server:
  port: 8083
spring:
  profiles: dev
--- #三个短横线分割多个profile区(文档快)

server:
  port: 8084
spring:
  profiles: prod #指定属于哪个环境

(3) 激活指定profile

  1. 在配置文件中指定spring.profiles.active=dev

  2. 命令行 --spring.profiles.active=dev

    java -jar spring-boot-01-0.0.1-SNAPSHOT.jar --spring.profiles.active

    可以直接在测试时,配置传入命令行参数

  3. jvm参数 -Dspring.profiles.active=dev

 

9.HttpEncodingAutoCOnfiguration为例解释自动配置原理;

@Configuration //表示这是一个配置类,以前编写的配置文件一样,也可以给融日中添加组件
@EnableConfigurationProperties({HttpEncodingProperties.class}) //启动指定类的ConfigurationProperties功能
@ConditionalOnWebApplication(
    type = Type.SERVLET
) //Spring底层@Conditional注解,根据不同的条件,如果满足指定的条件,整个配置类里面的配置就会生效;判断当前应用是否是web应用,如果是,当前配置类生效
@ConditionalOnClass({CharacterEncodingFilter.class}) // 判断当前项目有没有这个类  CharacterEncodingFilter:SpringMVC中进行乱码解决的过滤器;
@ConditionalOnProperty(
    prefix = "spring.http.encoding",
    value = {"enabled"},
    matchIfMissing = true
) // 判断配置文件中是否存在某个配置 spring.http.encoding.enabled;如果不存在,判断也是成立的 ,即使我们配置文件中不配置spring.http.encoding.enabled=true,默认也是生效的
public class HttpEncodingAutoConfiguration {
    //已经与springBoot的配置文件映射了
    private final HttpEncodingProperties properties;

    //有参构造器,参数的值就会从容器中拿
    public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {
        this.properties = properties;
    }
@Bean //给容器添加一个组件,这个组件的某些值需要从properties中获取 @ConditionalOnMissingBean public CharacterEncodingFilter characterEncodingFilter() { CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter(); filter.setEncoding(this.properties.getCharset().name()); filter.setForceRequestEncoding(this.properties.shouldForce( org.springframework.boot.autoconfigure.http.HttpEncodingProperties.Type.REQUEST)); filter.setForceResponseEncoding(this.properties.shouldForce( org.springframework.boot.autoconfigure.http.HttpEncodingProperties.Type.RESPONSE)); return filter; }
@ConfigurationProperties(
    prefix = "spring.http.encoding"
) // 从配置文件中获取指定的值和bean的属性进行绑定
public class HttpEncodingProperties {

 

所有在配置文件中能配置的属性都是在xxxxProperties类中封装;配置文件能配置什么就可以参照某个功能对应的这个属性类

一旦这个配置类生效;这个配置类就回个容器中添加各种组件;这些组件的属性是从对应的properties类中获取;

#我们能配置的属性都是来源于这个功能的properties类
spring.http.encoding.enabled=true
spring.http.encoding.charset=utf-8
spring.http.encoding.force=true

 

Spring Boot的精髓:

  1. SpringBoot启动回家再大量的自动配置类

  2. 我们需要的功能有没有SpringBoot默认写好的自动配置类

  3. 我们再看这个自动配置类中到底配置了哪些组件(只要我们要用的组件有,就不需要再配置)

  4. 给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们可以在配置文件中指定这些属性的值

xxxxAutoConfiguration自动配置类:自动给容器中添加组件

xxxxProperties:封装配置文件中相关属性

注意:自动配置类必须在一定条件下才能生效

我们可以启用debug=true属性;来让控制台打印自动配置类报告,这样我们就可以知道那些自动配置类生效;

其中Positive matches:(自动配置类启用的)

============================
CONDITIONS EVALUATION REPORT
============================


Positive matches:(自动配置类启用的)
-----------------

   CodecsAutoConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.http.codec.CodecConfigurer'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)

   CodecsAutoConfiguration.JacksonCodecConfiguration matched:
      - @ConditionalOnClass found required class 'com.fasterxml.jackson.databind.ObjectMapper'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
   WebSocketServletAutoConfiguration.TomcatWebSocketConfiguration#websocketContainerCustomizer matched:
      - @ConditionalOnMissingBean (names: websocketServletWebServerCustomizer; SearchStrategy: all) did not find any beans (OnBeanCondition)


Negative matches:(没有启动,没有匹配成功的自动配置类)
-----------------

   ActiveMQAutoConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)

  

posted @ 2018-10-15 22:54  MichaelKai  阅读(297)  评论(0编辑  收藏  举报