一、SpringBoot入门

1、SpringBoot简介

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

2、微服务

是一种架构风格(服务微化)

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

单体应用:ALL IN ONE

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

3、环境搭建

http://www.gulixueyuan.com/ 谷粒学院

环境约束

–jdk1.8:Spring Boot 推荐jdk1.7及以上;java version “1.8.0_112”

–maven3.x:maven 3.3以上版本;Apache Maven 3.3.9

–IntelliJIDEA2017:IntelliJ IDEA 2017.2.2 x64、STS

–SpringBoot 1.5.9.RELEASE:1.5.9;

统一环境;

4、Spring Boot Hello World

步骤:

1、创建一个maven工程

2、导入SpringBoot相关依赖POM文件

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.3.2.RELEASE</version>
  5. <relativePath/> <!-- lookup parent from repository -->
  6. </parent>
  7. <build>
  8. <plugins>
  9. <!--这个插件可以把应用打包成一个可以执行的jar包-->
  10. <plugin>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-maven-plugin</artifactId>
  13. </plugin>
  14. </plugins>
  15. </build>
  16. <dependencies>
  17. <!--添加对web应用的支持-->
  18. <dependency>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-web</artifactId>
  21. </dependency>
  22. </dependencies>

3、编写一个主程序类,启动Spring Boot应用

  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. /*标注这个是个主程序
  4. * */
  5. @SpringBootApplication
  6. public class HelloWorldMainApplication {
  7. public static void main(String[] args) {
  8. /*启动SpringBoot程序*/
  9. SpringApplication.run(HelloWorldMainApplication.class, args);
  10. }
  11. }

4、编写相关的Controller类

  1. import org.springframework.stereotype.Controller;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. import org.springframework.web.bind.annotation.ResponseBody;
  4. //Controller把该类标识为控制类
  5. @Controller
  6. public class HelloController {
  7. @ResponseBody
  8. @RequestMapping("/hello")
  9. public String hello() {
  10. return "HelloWorld";
  11. }
  12. }

5、运行主程序测试

直接运行main方法

6、简化部署

SpringBoot已经内置Tomcat,浏览器访问http://localhost:8080/hello

  1. <!-- 这个插件,可以将应用打包成一个可执行的jar包;-->
  2. <build>
  3. <plugins>
  4. <plugin>
  5. <groupId>org.springframework.boot</groupId>
  6. <artifactId>spring-boot-maven-plugin</artifactId>
  7. </plugin>
  8. </plugins>
  9. </build>

5、POM文件探究

1、POM文件

2、父项目

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.3.2.RELEASE</version>
  5. <relativePath/> <!-- lookup parent from repository -->
  6. </parent>
  7. 其父项目是
  8. <parent>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-dependencies</artifactId>
  11. <version>2.3.2.RELEASE</version>
  12. </parent>
  13. 他来真正管理Spring Boot应用里面的所有依赖版本;

Spring Boot的版本仲裁中心;

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

3、启动器

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>

spring-boot-starter-web:

  1. spring-boot-starterspring-boot场景启动器;帮我们导入了web模块正常运行所依赖的组件;

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

6、使用Spring Initializer快速创建Spring Boot项目

1、IDEA:使用 Spring Initializer快速创建项目

IDE都支持使用Spring的项目创建向导快速创建一个Spring Boot项目;

选择我们需要的模块;向导会联网创建Spring Boot项目;

默认生成的Spring Boot项目;

  • 主程序已经生成好了,我们只需要我们自己的逻辑
  • resources文件夹中目录结构
    • static:保存所有的静态资源; js css images;
    • templates:保存所有的模板页面;(Spring Boot默认jar包使用嵌入式的Tomcat,默认不支持JSP页面);可以使用模板引擎(freemarker、thymeleaf);
    • application.properties:Spring Boot应用的配置文件;可以修改一些默认设置;

2、STS使用 Spring Starter Project快速创建项目

二、配置文件

1、配置文件

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

•application.properties

•application.yml

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

2、YAML语言

1、简介

YAML(YAML Ain’t Markup Language)

YAML  A Markup Language:是一个标记语言

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

标记语言:

以前的配置文件;大多都使用的是  **xxxx.xml**文件;

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

YAML:配置例子

2、语法

1、基本语法

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

空格的缩进来控制层级关系;只要是左对齐的一列数据,都是同一个层级的

server:
    port: 8081
    path: /hello

属性和值也是大小写敏感;

2、值的写法

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

k: v:字面直接来写;

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

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

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

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

            name:   ‘zhangsan \n lisi’:输出;zhangsan \n  lisi

对象、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、配置文件值注入

1、使用yml格式的步骤

  1. 创建配置文件

    person:
    lastName: zhangsan
    age: 18
    boss: false
    birth: 2017/12/12
    maps: {k1: v1,k2: 12}
    lists:
     - lisi
     - zhaoliu
    dog:
     name: 小狗
     age: 2
    
  2. 我们可以导入配置文件处理器,以后编写配置就有提示了

    <!--导入配置文件处理器-->
    <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-configuration-processor</artifactId>
     <option>true</option>
    </dependency>
    
  3. 在JavaBean中设置映射

    /*
    * 使用注释将配置文件中的值映射到该组件中
    * 把配置文件中的所有属性和配置文件相关的配置进行绑定
    * 前缀表示与配置文件中那个属性进行映射
    * 只有这个组件容器中的组件,才能容器中提供功能
    * 默认是全局的配置文件,如果需要读取指定的配置文件
    * */
    @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;
    
  4. 测试 ```java /*

  • 可以在测试期间进行类似编码一样的自动注入
  • */ @SpringBootTest class SpringbootdemoApplicationTests { @Autowired Person person; @Test void contextLoads() {
      System.out.println(person);
    
    } } ```

2、使用properties格式的步骤

  1. 创建配置文件
    person.last-name=zhangsan
    person.age=18
    person.birth=2017/12/12
    person.boss=false
    person.maps.k1=v1
    person.maps.k2=12
    person.lists=a,b,c
    person.dog.name=dog
    person.dog.age=2
    

其余步骤于以上方式一相同

properties配置文件在ide中可能会出现乱码,properties默认编码是UTF-8

调整

4、JavaBean中@Value获取值和@ConfigurationProperties获取值比较

@ConfigurationProperties @Value
功能 批量注入配置文件中的属性 逐个注入
SpEL 不支持 不支持
JSR303数据校验 支持 不支持
复杂类型的封装 支持 不支持

配置文件tml还是properties都可以获取值

如果只是在某个业务逻辑中获取某项值,使用@Value

如果专门编写了一个JavaBean来和配置文件进行映射,使用@ConfigurationProperties

1、@ConfigurationProperties

/*
 * 使用注释将配置文件中的值映射到该组件中
 * 把配置文件中的所有属性和配置文件相关的配置进行绑定
 * 前缀表示与配置文件中那个属性进行映射
 * 只有这个组件容器中的组件,才能容器中提供功能
 * */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {}

2、@Value

@Component
public class Person {
    @Value("${person.last-name}")
    private String lastName;
}

4、获取指定的配置文件

1、@PropertySource

在JavaBean之上使用@PropertySource(value = (“classpath:other.properties”)),获取指定的配置文件,

/*加载指定的配置文件
 * */
@PropertySource(value = ("classpath:other.properties"))
@Component
@ConfigurationProperties(prefix = "person")
public class Person {}

2、@ImportResource

导入Spring的xml配置文件,使得配置文件生效,因为默认状态下SpringBoot 是不会自动加载xml配置文件的,需要在启动类中设置,不推荐

Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;想让Spring的配置文件生效,加载进来

@ImportResource(locations = {"classpath:bean.xml"})
@SpringBootApplication
public class SpringbootdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootdemoApplication.class, args);
    }
}

3、配置类,

SpringBoot推荐使用全注解的方式,创建配置类,这个配置类就相当于SSM中xml配置文件

1、配置类@Configuration ———>Spring配置文件

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

import com.example.springbootdemo.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/*这个配置类就相当于SSM中xml配置文件*/
@Configuration
public class MyAppConfig {
    /*将方法的返回值添加到容器中,容器中的这个组件默认的id就是方法名*/
    @Bean
    public HelloService helloService() {
        return new HelloService();
    }
}

4、配置文件的占位符

SpringBoot - 图1

server.port=8081
person.last-name=zhangsan${random.uuid}
person.age=${random.int}}
person.birth=2017/12/12 
person.boss=false
person.maps.k1=v1
person.maps.k2=12
person.lists=a,b,c
person.dog.name=${person.last-name}_dog
person.dog.age=2

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.hello:hello}_dog
person.dog.age=15

5、Profile

image-20200818112948459

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

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

2、命令行:

    java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev;

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

3、虚拟机参数;

    -Dspring.profiles.active=dev

6、配置文件加载的位置

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

–file:./config/ –file:./ –classpath:/config/ –classpath:/

优先级由高到底,高优先级的配置会覆盖低优先级的配置;SpringBoot会从这四个位置全部加载主配置文件;互补配置

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

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

java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar —spring.config.location=G:/application.properties

7、外部配置加载顺序

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

1.命令行参数

所有的配置都可以在命令行上进行指定

java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar —server.port=8087 —server.context-path=/abc

多个配置用空格分开; —配置项=值

2.来自java:comp/env的JNDI属性

3.Java系统属性(System.getProperties())

4.操作系统环境变量

5.RandomValuePropertySource配置的random.*属性值

由jar包外向jar包内进行寻找;

优先加载带profile

6.jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件

7.jar包内部的application-{profile}.properties或application.yml(带spring.profile)配置文件

再来加载不带profile

8.jar包外部的application.properties或application.yml(不带spring.profile)配置文件

9.jar包内部的application.properties或application.yml(不带spring.profile)配置文件

10.@Configuration注解类上的@PropertySource

11.通过SpringApplication.setDefaultProperties指定的默认属性

所有支持的配置加载来源;

参考官方文档

8、自动配置原理

  1. SpringBoot启动的时候加载主配置类,开启了自动配置功能 @EnableAutoConfiguration
  2. @EnableAutoConfiguration 作用:
    1. 利用EnableAutoConfigurationImportSelector给容器中导入一些组件?
    2. 可以查看selectImports()方法的内容;
    3. List configurations = getCandidateConfigurations(annotationMetadata, attributes);获取候选的配置
      SpringFactoriesLoader.loadFactoryNames()
      扫描所有jar包类路径下  META-INF/spring.factories
      把扫描到的这些文件的内容包装成properties对象
      从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加在容器中
      

将 类路径下 META-INF/spring.factories 里面配置的所有EnableAutoConfiguration的值加入到了容器中;

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.DeviceResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration,\
org.springframework.boot.autoconfigure.social.FacebookAutoConfiguration,\
org.springframework.boot.autoconfigure.social.LinkedInAutoConfiguration,\
org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration

1、日志框架

框架用于记录系统的一些运行信息,日志框架架包

常见的日志框架:JUL、JCL、

日志门面(日志的抽象层) 日志实现
JCL、SLF4j

SpringBoot选用SLF4j和logback

2、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");
  }
}

image-20200818155226237

四、Spring Boot与Web开发

使用SpringBoot

  1. 创建SpringBoot应用,选中需要的模块
  2. 指定生成的配置文件
  3. 写业务代码

自动配置的原理

SpringBoot对静态资源的映射

public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
    } else {
        Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
        CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
        if (!registry.hasMappingForPattern("/webjars/**")) {
            this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
        }

        String staticPathPattern = this.mvcProperties.getStaticPathPattern();
        if (!registry.hasMappingForPattern(staticPathPattern)) {
            this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
        }

    }
}
classpath:/META-INF/resources/", 
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/
/表示当前静态资源的根目录

模板引擎

SpringBoot 推荐的模板引擎,Thymeleaf

引入Thmleaf

Thymeleaf语法

4、SpringMVC自动配置

SpringMVC auto-configuration

拓展SpringMVC

编写一个配置类(@Configuration),实现WebMvcConfigurer接口

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/test1").setViewName("success");
    }
}

全面接管SpringMVC

如果需要自己配置所有的SpringMVC参数,则再配置类中添加@EnableWebMvc即可,这时所有自动配置的SpringMVC功能会失效

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@EnableWebMvc
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/test1").setViewName("success");
    }
}

5、如何修改SpringBoot的默认配置

6、RestfulCRUD

1、默认访问首页

2、国际化

编写国家化

SpringBoot - 图4

3、登陆

模板引擎页面需要实时生效的方法:

1.禁用模板引擎的缓存

#application.properties中开发时禁用模板缓存
spring.thymeleaf.cache=false

2.页面修改后按下ctrl+F9重新编译

显示登陆错误信息

<!--判断msg不为空,并提示错误信息-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

3、拦截器进行登陆检查

新建拦截器类

package com.example.springbootdemo.componet;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*拦截器类*/
public class LoginHandlerInterceptor implements HandlerInterceptor {
    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        if (user == null) {
            /*转发前需要带上错误消息*/
            request.setAttribute("mag", "没有权限登陆");
            /*未登陆拦截请求,并跳转会主页面*/
            request.getRequestDispatcher("/index").forward(request, response);
            return false;
        } else {
            //已经登陆放行请求
            return true;
        }
    }
}

SpringMVC配置类中注册拦截器

//注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
    /*
    *静态资源:*.css,*.js
    * SpringBoot已经做好了静态资源的映射
    * /**表示拦截所有请求,
    * excludePathPatterns表示例外
    * */
    registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").
            excludePathPatterns("/","/index","/user/login");
}

5、RestfulCRUD:CRUD满足Rest风格

7、SpringBoot默认的错误处理机制

默认效果:

  1. 浏览器返回一个默认的错误页面
  2. 客户端,返回json数据

如何定制

8、配置嵌入式的Servlet容器

1、如何定制和修改Servlet容器的相关配置

2、注册Servlet的三大组件

3、如何使用其他Servlet容器

Jetty(一帮应用于长连接)

Undertow(不支持JSP,)


6. 



7.

五、SpringBoot与数据访问

1、JDBC

2、整合Druid数据源

3、整合MyBatis

1、初始步骤

1、映入依赖

<!--引入Mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.0</version>
</dependency>

2、配置数据源

package com.example.springbootdemo.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/*Druid的配置类*/
@Configuration
public class DruidConfig {
    /*配置前缀使得yml中参数的只生效*/
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid() {
        return new DruidDataSource();
    }
    /*配置Druid的监控*/
    //1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        /*初始化参数*/
        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "admin");
        initParams.put("loginPassword", "password");
        initParams.put("allow","") ;//默认就是允许所有人访问
        //initParams.put("deny", "");//拒绝某个地址访问
        bean.setInitParameters(initParams);
        return bean;
    }
    //2、配置一个web监控
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map<String, String> initParams = new HashMap<>();
        initParams.put("exclusions", "*.js,*.css");//排除拦截哪些文件
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

3、创建数据表

4、创建JavaBean

2、配置方式

完成基本配置

1、注解版

自动一MyBatis的配置规则:给容器中添加一个ConfigurationCustomizer

import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
    public ConfigurationCustomizer configurationCustomizer() {
        return new ConfigurationCustomizer(){
            @Override
            public void customize(Configuration configuration) {
                /*开启驼峰命名法*/
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

创建一个Mapper接口,Springboot会根据注解完成映射

package com.example.springbootdemo.mapper;
import com.example.springbootdemo.bean.Department;
import org.apache.ibatis.annotations.*;
/*注解版,实际开发中一般简单的项目使用注解版,如果复杂*/
/*创建一个操作数据库的配置类*/
@Mapper
public interface DepartmentMapper {
    @Select("select * from department where id=#{id}")
    public Department getDepartment(Integer id);
    @Delete("delete from department where id=#{id}")
    public int deleteDeptById(Integer id);
    /*设置id为封装组件用*/
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);
    @Update("update department set departmentName=#{departmentName} where id=#{id}")
    public int updateDept(Department department);
}

使用Mappscan批量扫描为mapper类添加注解

/*在SpringBoot的启动类中自动为包中的所有Mapper类添加@Mapper注解*/
@MapperScan(value = "com.example.springbootdemo.mapper")
@SpringBootApplication
public class SpringbootdemoApplication {...}

2、配置版

创建一个Mapper接口

import com.example.springbootdemo.bean.Employee;
public interface EmployeeMapper {
    public Employee getEmpById(Integer id);
    public void insertEmp(Employee employee);
}

创建对应的xml配置文件

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--设置驼峰命名法-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings> 
<!--此处已经使用了Druid作为数据源,因此原有的配置可以删除-->
<!--<settings>
    &lt;!&ndash;设置mybatis日志&ndash;&gt;
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC"/>
        <dataSource type="POOLED">
            <property name="driver" value="${}}"/>
            <property name="url" value=""/>
            <property name="username" value=""/>
            <property name="password" value=""/>
        </dataSource>
    </environment>
</environments>
<mappers>
    <mapper resource=""/>
</mappers>-->
</configuration>

XXXMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.springbootdemo.mapper.EmployeeMapper">
    <select id="getEmpById" resultType="com.example.springbootdemo.bean.Employee">
        SELECT * FROM employee WHERE id=#{id};
    </select>
    <insert id="insertEmp">
        INSERT INTO employee(lastName, email, gender, d_id)
        VALUES (#{lastName},#{email},#{gender},#{dId})
    </insert>
</mapper>

指定全局配置文件在SpringBoot的主配置文件中加载Mybatis的xml配置文件路径

在application.yml中

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

4、整合JPA