一:SpringBoot简介

  当前互联网后端开发中,JavaEE占据了主导地位。对JavaEE开发,首选框架是Spring框架。在传统的Spring开发中,需要使用大量的与业务无关的XML配置才能使Spring框架运行起来,这点备受许多开发者诟病。随着Spring4.x发布,Spring已经完全脱离XML,只使用注解就可以运行项目。为了进一步简化Spring应用的开发,SpringBoot诞生了。它是由Pivotal团队提供的全新框架,其设计目的是简化Spring应用的搭建及开发过程,并迎合时下流行的分布式微服务设计思想,越来越多企业在使用SpringBoot

1:设计初衷

  SpringBoot为我们开发者提供了一种更快速、体验更好的开发方式,我们可以开箱即用,无需像写Spring那样配置各种XML文件,虽然Spring3.0时引入了基于java的配置,但是编写这些配置无疑是在浪费大量时间,其实SpringBoot还内置Tomcat

2:核心功能

  1. 一:独立的运行Spring
  2. SpringBoot 可以以jar包形式独立运行,运行一个SpringBoot项目只需要通过java -jar xx.jar来运行
  3. 二:内置Servlet容器
  4. Spring Boot可以选择内嵌Tomcatjetty或者Undertow,这样我们无须以war包形式部署项目
  5. 三:简化Maven配置
  6. SpringBoot提供了一系列的start pom来简化Maven的依赖加载,例如,当你使用了spring-boot-starter-web
  7. 四:自动装配
  8. SpringBoot会根据在类路径中的jar包,类、为jar包里面的类自动配置Bean,这样会极大地减少我们要使用的配置。
    当然,SpringBoot只考虑大多数的开发场景,并不是所有的场景,若在实际开发中我们需要配置Bean,而SpringBoot
    没有提供支持,则可以自定义自动配置
  9. 五:准生产的应用监控
  10. SpringBoot提供基于http ssh telnet对运行时的项目进行监控
  11. 六:无代码生产和xml配置
  12. SpringBoot不是借助与代码生成来实现的,而是通过条件注解来实现的,这是Spring4.x提供的新特性

Spring Boot只是Spring本身的扩展,使开发,测试和部署更加方便

3:本文开发环境需求

  SpringBoot 2.4.1正式发行版,要求Java8并且兼容Java15;对应的Spring版本是5.3.2;而且要求Maven 3.3+ 但是最好使用3.5.4稳定版本,而Servlet容器的版本为Tomcat9.0(Servlet Version 4.0)、Jetty 9.4(Servlet Version 3.1)、Undertow 2.0(Servlet Version 4.0)

二:SpringBoot入门搭建

1:手动搭建案例

  我们以一个简单的SpringBoot案例来突显出Spring的繁琐,我接下来将使用SpringBoot来实现一个简单的带Controller的案例

  1. 第一步:使用IDEA构建一个普通的Maven项目
    第二步:在构建好的maven工程中对pom文件修改
    第三步:编写启动引导类
    第四步:编写Controller
    第五步:访问(默认8080端口) 以本案例http://localhost:8080/index/test

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <!--
  8. 在编写SpringBoot的项目时我们得继承SpringBoot的父POM文件,
  9. 这一点和我们以前使用Spring导入的坐标不太一样,细心的会查看
  10. 继承的父POM文件后发现SpringBoot为我们提前导入了大量的坐标,
  11. 这就解决了我们平常导入坐标版本冲突问题
  12. -->
  13. <parent>
  14. <artifactId>spring-boot-starter-parent</artifactId>
  15. <groupId>org.springframework.boot</groupId>
  16. <version>2.4.1</version>
  17. </parent>
  18.  
  19. <groupId>org.example</groupId>
  20. <artifactId>demo0023</artifactId>
  21. <version>1.0-SNAPSHOT</version>
  22.  
  23. <dependencies>
  24. <!--
  25. 要编写SpringMVC相关代码我们还得导入web的starter依赖
  26. SpringBoot为了我们导入的方便,把一系列的关于SpringMVC的坐标打包结合到了
  27. 这个我下面导入的坐标里面
  28. -->
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-web</artifactId>
  32. </dependency>
  33. </dependencies>
  34. </project>

pom.xml里面添加相应坐标

  1. package cn.xw;
  2.  
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5.  
  6. /**
  7. * 启动引导类
  8. */
  9. //加上此注解代表当前类就是SpringBoot启动类,否则就是普通类
  10. @SpringBootApplication
  11. public class SpringBoot5Application {
  12. //SpringBoot程序入口
  13. public static void main(String[] args) {
  14.  
  15. //main函数里面的args参数是一个String数组,所以在main函数运行的
  16. //同时可以接收参数,接收过来的参数交给了SpringBoot,用于后期运行配置,后面介绍
  17. //第一个参数通过反射是告诉SpringBoot哪个是启动引导类
  18. //还有这个方法有个返回值,返回IOC容器
  19. SpringApplication.run(SpringBoot5Application.class, args);
  20. }
  21. /**
  22. * 注意:此类只会扫描加载当前包及其子包里面的全部类,然会把它们加载IOC容器中
  23. */
  24. }

启动引导类编写

  1. package cn.xw.controller;
  2.  
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5.  
  6. @RestController //结合@ResponseBody 和 @Controller 两注解
  7. @RequestMapping("/index")
  8. public class IndexController {
  9. @RequestMapping("/test")
  10. public String testMethod() {
  11. System.out.println("访问到此方法");
  12. return "Hello !!";
  13. }
  14. }

Controller编写

2:使用Spring Initializr快速搭建

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <!--SpringBoot父POM坐标-->
  6. <parent>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-parent</artifactId>
  9. <version>2.4.1</version>
  10. <relativePath/>
  11. </parent>
  12. <groupId>cn.xw</groupId>
  13. <artifactId>springboot_test</artifactId>
  14. <version>0.0.1-SNAPSHOT</version>
  15. <name>springboot_test</name>
  16. <description>Demo project for Spring Boot</description>
  17.  
  18. <properties>
  19. <java.version>1.8</java.version>
  20. </properties>
  21.  
  22. <dependencies>
  23. <!--WEB开发Starter-->
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-web</artifactId>
  27. </dependency>
  28. <!--SpringBoot的开发者工具-->
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-devtools</artifactId>
  32. <scope>runtime</scope>
  33. <optional>true</optional>
  34. </dependency>
  35. <!--SpringBoot测试Starter-->
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-test</artifactId>
  39. <scope>test</scope>
  40. </dependency>
  41. </dependencies>
  42.  
  43. <build>
  44. <plugins>
  45. <!--SpringBoot的Maven插件-->
  46. <plugin>
  47. <groupId>org.springframework.boot</groupId>
  48. <artifactId>spring-boot-maven-plugin</artifactId>
  49. </plugin>
  50. </plugins>
  51. </build>
  52. </project>

自动创建的Maven坐标说明

三:SpringBoot基本分析

1:坐标中starters分析及依赖管理

  starter是依赖关系的整理和封装。是一套依赖坐标的整合,可以让导入应用开发的依赖坐标更方便。利用依赖传递的特性帮我们把一些列指定功能的坐标打包成了一个starter,我们只需要导入starter即可,无需导入大量坐标;每个Starter包含了当前功能下的许多必备依赖坐标这些依赖坐标是项目开发,上线和运行必须的。同时这些依赖也支持依赖传递。如下Starter:

  1. <!--导入WEB开发Starter-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter</artifactId>
  5. <version>2.4.1</version>
  6. <scope>compile</scope>
  7. </dependency>
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-json</artifactId>
  11. <version>2.4.1</version>
  12. <scope>compile</scope>
  13. </dependency>
  14. <dependency>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-tomcat</artifactId>
  17. <version>2.4.1</version>
  18. <scope>compile</scope>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.springframework</groupId>
  22. <artifactId>spring-web</artifactId>
  23. <version>5.3.2</version>
  24. <scope>compile</scope>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework</groupId>
  28. <artifactId>spring-webmvc</artifactId>
  29. <version>5.3.2</version>
  30. <scope>compile</scope>
  31. </dependency>
  32. </dependencies>

spring-boot-starter-web内部封装的一些列坐标

封装成各个Starter的好处就是让我们更加专注于业务开发,无需关心依赖导入,依赖冲突,及依赖的版本

问:为什么导入的一些Starter不需要写版本呢?

  不指定版本是因为maven有依赖传递的特性,可推测starter在父级定义了并锁定了版本;spring-boot-dependencies.xml 文件可以给大家一个答案;继承关系为 spring-boot-starter-parent.xml ==> spring-boot-dependencies.xml 这里面锁定了我们常用的坐标及Stater

编写SpringBoot项目继承spring-boot-starter-parent的好处和特点

  1. ①:默认编译Java 1.8
  2. ②:默认编码UTF-8
  3. ③:通过spring-boot-denpendenciespom管理所有公共Starter依赖的版本
  4. ④:spring-boot-denpendencies通过Maven的依赖传递和版本锁定特性来实现版本管理
  5. ⑤:随用随取,不用继承父类所有的starter依赖。

POM文件中的Maven插件功能

  1. <build>
  2.   <plugins>
  3. <!-- 作用:将一个SpringBoot的工程打包成为可执行的jar包 -->
  4.    <plugin>
  5.    <groupId>org.springframework.boot</groupId>
  6. <artifactId>spring-boot-maven-plugin</artifactId>
  7.    </plugin>
  8.   </plugins>
  9. </build>

补充:可选择的启动器官网介绍,需要则查询这个手册

2:自动配置(AutoConfiguration)分析

  所有我们要配置的项目Pivotal团队的开发人员,帮我们写好了,怎么实现的,主要是通过@Configuration实现 SpringBoot采用约定大于配置设计思想,将所有可能遇到的配置信息提前配置好,写在自动配置的jar包中。每个Starter基本都会有对应的自动配置。SpringBoot帮我们将配置信息写好,存放在一个jar包中:spring-boot-autoconfigure-2.4.1.jar;jar包里,存放的都是配置类,让配置类生效的"规则类"

  1. 接下来我来介绍一个我们常见的配置类
  2. 一:找到项目的External Libraries
  3. 二:查找Maven:org.springframework.boot:spring-autoconfigue:2.4.1
  4. 三:内部有个spring-boot-autoconfigue-2.4.1.jar
  5. 四:点击org ==> web ==> servlet ==> ServletWebServerFactoryAutoConfiguration
  6.  
  7. @Configuration(proxyBeanMethods = false) //代表是个配置类 SpringBoot为我们提供的每个配置类都有此注解
  8. @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
  9. @ConditionalOnClass(ServletRequest.class)
  10. @ConditionalOnWebApplication(type = Type.SERVLET)
  11. @EnableConfigurationProperties(ServerProperties.class)
  12. @Import({ ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class,
  13. ServletWebServerFactoryConfiguration.EmbeddedTomcat.class,
  14. ServletWebServerFactoryConfiguration.EmbeddedJetty.class,
  15. ServletWebServerFactoryConfiguration.EmbeddedUndertow.class })
  16. public class ServletWebServerFactoryAutoConfiguration { ... }
  17.  
  18. 补充:我们回到之前点击META-INF ==> spring.factories 这里面配置的是SpringBoot的全部配置类
    补充:我们回到之前点击META-INF ==> spring-configuration-metadata.json 这里面配置着各种配置类的信息参数

问:SpringBoot提供这么多配置类,难道是程序运行后就全部导入吗?

  不会全部导入,只会根据当前项目的需求选择性的装配所需的配置类,这也是SpringBoot的自动装配一大特性;我们也可以设想一下,一次性装配全部配置类,那该多慢呀;

问:SpringBoot怎么知道程序运行后就自动装配呢?

  我们找到SpringBoot入口函数,点开 @SpringBootApplication 注解会发现里面有个 @EnableAutoConfiguration 这个注解就是开启自动配置的

问:开启自动装配后,它咋知道要加载指定配置呢?那么多配置类呢

  我们继续看上面的 ServletWebServerFactoryAutoConfiguration 配置类

  1. @Configuration(proxyBeanMethods = false)
  2. @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
  3. //配置类能否被自动装配主要看 @ConditionalOnClass注解
  4. //此注解是否可以加载到一个叫 ServletRequest.class文件,一旦存在则自动装配
  5. @ConditionalOnClass(ServletRequest.class)
  6. @ConditionalOnWebApplication(type = Type.SERVLET)
  7. @EnableConfigurationProperties(ServerProperties.class)
  8. @Import({ ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class,
  9. ServletWebServerFactoryConfiguration.EmbeddedTomcat.class,
  10. ServletWebServerFactoryConfiguration.EmbeddedJetty.class,
  11. ServletWebServerFactoryConfiguration.EmbeddedUndertow.class })
  12. public class ServletWebServerFactoryAutoConfiguration { ... }

  有了自动配置后,那么基本全部采用默认配置(这也就是为啥说约定大于配置的思想);那么要修改默认配置也是可以的,我们只需在配置文件配置指定的参数即可 官方全部可配置属性  如下常见配置:

  1. # 端口配置
  2. server.port=8888
  3. # 配置context-path项目访问根路径
  4. server.servlet.context-path=/demo
  5. # 开启debug模式,详细日志输出,用于开发的一种设置 默认是false
  6. debug=true
  7. # 配置日志 logging.level.{指定包下的日志}=debug
  8. logging.level.cn.xw=debug

四:SpringBoot的配置文件

  SpringBoot是约定大于配置的,配置都有默认值。如果想修改默认配置,可以使用application.properties或application.yml或application.yaml自定义配置。SpringBoot默认从Resource目录加载自定义配置文件。application.properties是键值对类型;application.yml是SpringBoot中一种新的配置文件方式,在使用自定义配置时名称一定要为application,因为是提前约定好的,而且三个后缀名的文件都写上是有个先后顺序,后面可覆盖前面

  1. <includes>
  2. <include>**/application*.yml</include>
  3. <include>**/application*.yaml</include>
  4. <include>**/application*.properties</include>
  5. </includes>

  1. # properties类型配置文件 application.properties
  2. server.port=8080
  3. server.address=127.0.0.1
  4.  
  5. <!--xml类型配置文件 application.xml-->
  6. <server>
  7. <port>8080</port>
  8. <address>127.0.0.1</address>
  9. </server>
  10.  
  11. # yml/yaml类型配置文件 application.yml/ymal
  12. server:
  13. port: 8080
  14. address: 127.0.0.1

三种类型文件的配置方式

1:yml/yaml配置文件语法及使用

  YML文件格式是YAML(YAML Aint Markup Language)编写的文件格式。可以直观被电脑识别的格式。容易阅读,容易与脚本语言交互。可以支持各种编程语言(C/C++、Ruby、Python、Java、Perl、C#、PHP)。以数据为核心,比XML更简洁。扩展名为.yml或.yaml  官方网站  在线properties转yml

  1. 1:大小写敏感
  2. 2:数据值前边必须有空格,作为分隔符
  3. 3:使用缩进表示层级关系
  4. 4:缩进不允许使用tab,只允许空格
  5. 5:缩进的空格数不重要,只要相同层级的元素左对齐即可
  6. 6"#"表示注释,从这个字符一直到行尾,都会被解析器忽略。
  7. 7:数组和集合使用 "-" 表示数组每个元素

  1. # 单个值指定
  2. name: 小周
  3. # 单引号忽略转义字符
  4. message1: 'hello \n world'
  5. # 双引号识别转义字符 打印时会换行
  6. message2: "hello \n world"
  7.  
  8. # 对象方式指定 普通写法
  9. student:
  10. name: 张三
  11. age: 25
  12. address: 安徽六安
  13. # 对象方式指定 行内写法
  14. teacher: { name: 李老师, age: 50, address: 上海 }
  15.  
  16. # 数组方式 普通写法
  17. hobby:
  18. - baseball
  19. - basketball
  20. - volleyball
  21. # 数组方式 行内写法
  22. likes: [ baseball, basketball, volleyball ]
  23.  
  24. # 集合方式 map等格式
  25. peoples:
  26. key1: zhangsan
  27. key2: anhui
  28. key3: xiezi
  29. # 集合方式 map等格式 行内写法
  30. peoples1: { key1 : zhangsan, key2 : anhui , key3 : shanghai}
  31. # 这上面的key~ 是具体的key名称
  32.  
  33. ######## 其它方式扩展
  34. # 配置引用
  35. bookName: 零基础学Java
  36. person:
  37. name: xiaowu
  38. likeBookName: ${bookName}
  39.  
  40. # 配置随机数 其中有int 和 long两种根据情况选择
  41. # 随机字符串
  42. StringA: ${random.value}
  43. # 随机数
  44. numberB: ${random.int}
  45. # 随机产出小于10的数
  46. numberC: ${random.int(10)}
  47. # 随机产出10~100之间的数 大于10小于100
  48. numberD: ${random.int(10,100)}
  49. # 随机产出一个uuid字符串
  50. uuid: ${random.uuid}

yml基本格式写法

2:配置文件与配置类属性映射

(1):java配置获取基本的配置文件信息.properties类型

  1. 三:配置类 jdbcConfig.java
  2. //声明此类为配置类
  3. @Configuration
  4. //导入外部配置文件 因为这个配置类是自定义的,不受SpringBoot帮我们管理
  5. @PropertySource(value="classpath:application.properties")
  6. public class JdbcConfig {
  7.  
  8. @Value(value = "${jdbc.datasource.driver-class-name}")
  9. private String driver;
  10. @Value("${jdbc.datasource.url}")
  11. private String url;
  12. @Value("${jdbc.datasource.username}")
  13. private String username;
  14. @Value("${jdbc.datasource.password}")
  15. private String password;
  16.  
  17. @Bean(value = "dataSource")
  18. public DataSource getDataSource() {
  19. System.out.println(driver);
  20. //创建连接池 并加入容器
  21. DruidDataSource dataSource = new DruidDataSource();
  22. dataSource.setDriverClassName(driver);
  23. dataSource.setUrl(url);
  24. dataSource.setUsername(username);
  25. dataSource.setPassword(password);
  26. return dataSource;
  27. }
  28. }
  29.  
  30. 四:Controller 通过访问运行程序 这里就先不写测试类
  31. @RestController //结合@ResponseBody 和 @Controller 两注解
  32. @RequestMapping("/index")
  33. public class IndexController {
  34.  
  35. @Autowired
  36. private DataSource dataSource;
  37.  
  38. @RequestMapping("/test")
  39. public String testMethod() {
  40. System.out.println("访问到此方法"+dataSource);
  41. return "Hello !!";
  42. }
  43. }
  44.  
  45. //打印
  46. 访问到此方法{
  47. CreateTime:"2021-01-09 15:22:49",
  48. ActiveCount:0,
  49. PoolingCount:0,
  50. CreateCount:0,
  51. DestroyCount:0,
  52. CloseCount:0,
  53. ConnectCount:0,
  54. Connections:[
  55. ]
  56. }

基本数据获取.properties

(2):java配置获取基本的配置文件信息并注入.yml/.yaml类型

  1. 1、使用注解@Value映射
  2.   @value注解将配置文件的值映射到Spring管理的Bean属性值,只能映射基本数据类型
  3. 2、使用注解@ConfigurationProperties映射
  4.   通过注解@ConfigurationProperties(prefix=''配置文件中的key的前缀")可以将配置文件中的配置自动与实体进行映射。
      使用@ConfigurationProperties方式必须提供Setter方法,使用@Value注解不需要Setter方法
    注:使用@ConfigurationProperties要在主函数上开启@EnableConfigurationProperties

  1. /**
  2. * @author: xiaofeng
  3. * @date: Create in $DATE
  4. * @description: 学生对象
  5. * @version: v1.0.0
  6. */
  7. @Component //一定要保证被映射注入的是个组件
  8. @ConfigurationProperties(prefix = "student") //可以之间映射对象
  9. public class Student {
  10. private Integer id; //id
  11. private String name; //姓名
  12. private String address; //住宅
  13. private List<String> hobbys; //爱好
  14. private Map<String, List<Integer>> score;//各科得分
  15. private Map<String,Teacher> teachers; //各科老师
  16. //...省略get/set 这个一定要写 我为了代码少没复制
  17. }
  18.  
  19. /**
  20. * @author: xiaofeng
  21. * @date: Create in $DATE
  22. * @description: 老师对象
  23. * @version: v1.0.0
  24. */
  25. public class Teacher {
  26. private String name;
  27. private String message;
  28. }
  29.  
  30. //注:在添加完@ConfigurationProperties后如果没有spring-boot-configuration-processor编译器会弹出提示
  31. //提示信息:Spring Boot Configuration Annotation Processor.....
  32. //pom.xml添加这个配置注解处理器
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-configuration-processor</artifactId>
  36. <optional>true</optional>
  37. </dependency>
  38. //然后去主函数类上面添加@EnableConfigurationProperties 开启配置注解处理器

POJO实体类

  1. student:
  2. id: 1001
  3. name: 张三
  4. address: 安徽六安
  5. hobbys:
  6. - baseball
  7. - basketball
  8. - volleyball
  9. score:
  10. yuwen:
  11. - 66
  12. - 88
  13. shuxue:
  14. - 85
  15. - 99
  16. #简写 score: { "yuwen" : [58,99], "shuxue" : [88,96] }
  17. # 这里通过外界传入值 注意引号别忘了
  18. teachers:
  19. yuwenTeacher: { name: "${teacherNameA}", message: "${teacherMessageA}" }
  20. shuxueTecher: { name: "${teacherNameB}", message: "${teacherMessageB}" }
  21.  
  22. teacherNameA: 张老师
  23. teacherMessageA: 教语文
  24. teacherNameB: 李老师
  25. teacherMessageB: 教数学

application.yml配置文件

  1. //通过web的方式加载程序运行
    @RestController //结合@ResponseBody 和 @Controller 两注解
  2. @RequestMapping("/index")
  3. public class IndexController {
  4.  
  5. //注入
  6. @Autowired
  7. private Student student;
  8.  
  9. @RequestMapping("/test")
  10. public String testMethod() {
  11. System.out.println(student.toString());
  12. //Student{
  13. // id=1001,
  14. // name='张三',
  15. // address='安徽六安',
  16. // hobbys=[baseball, basketball, volleyball],
  17. // score={yuwen=[66, 88], shuxue=[85, 99]},
  18. // teachers={yuwenTeacher=Teacher{name='张老师', message='教语文'},
  19. // shuxueTecher=Teacher{name='李老师', message='教数学'}}}
  20. return "Hello !!";
  21. }
  22. }

五:SpringBoot与其它技术集成

1:SpringBoot集成MyBatis 建表语句

  集成Mybatis完成查询全部

(1):使用注解方式完成集成

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. https://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <parent>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-parent</artifactId>
  10. <version>2.4.1</version>
  11. <relativePath/> <!-- lookup parent from repository -->
  12. </parent>
  13. <groupId>cn.xw</groupId>
  14. <artifactId>demomybatiss</artifactId>
  15. <version>0.0.1-SNAPSHOT</version>
  16. <name>demomybatiss</name>
  17. <description>Demo project for Spring Boot</description>
  18.  
  19. <properties>
  20. <java.version>1.8</java.version>
  21. </properties>
  22. <dependencies>
  23. <!--web启动器-->
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-web</artifactId>
  27. </dependency>
  28. <!--spring-boot启动器-->
  29. <dependency>
  30. <groupId>org.mybatis.spring.boot</groupId>
  31. <artifactId>mybatis-spring-boot-starter</artifactId>
  32. <version>2.1.4</version>
  33. </dependency>
  34. <!--工具-->
  35. <dependency>
  36. <groupId>org.springframework.boot</groupId>
  37. <artifactId>spring-boot-devtools</artifactId>
  38. <scope>runtime</scope>
  39. <optional>true</optional>
  40. </dependency>
  41. <!--mysql驱动-->
  42. <dependency>
  43. <groupId>mysql</groupId>
  44. <artifactId>mysql-connector-java</artifactId>
  45. <scope>runtime</scope>
  46. </dependency>
  47. <!--测试 这里没用到-->
  48. <dependency>
  49. <groupId>org.springframework.boot</groupId>
  50. <artifactId>spring-boot-starter-test</artifactId>
  51. <scope>test</scope>
  52. </dependency>
  53. </dependencies>
  54. <build>
  55. <plugins>
  56. <plugin>
  57. <groupId>org.springframework.boot</groupId>
  58. <artifactId>spring-boot-maven-plugin</artifactId>
  59. </plugin>
  60. </plugins>
  61. </build>
  62. </project>

pom.xml文件

  1. spring:
  2. datasource:
  3. driver-class-name: com.mysql.cj.jdbc.Driver
  4. url: jdbc:mysql://127.0.0.1:3306/demo_school?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
  5. username: root
  6. password: 123
  7. # 加上 ?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC 是为了防止SpringBoot报时区错误
  8. # com.mysql.jdbc.Driver 这种的已经过时了,但是不代表就剔除了 可以用

resources下的application.yml配置文件

  1. ///////////POJO
  2. /**
  3. * @author: xiaofeng
  4. * @date: Create in $DATE
  5. * @description: 学生实体类
  6. * @version: v1.0.0
  7. */
  8. public class Student implements Serializable {
  9. private int id; //id
  10. private String name; //姓名
  11. private String sex; //性别
  12. private int age; //年龄
  13. private double credit; //成绩/学分
  14. private double money; //零花钱
  15. private String address; //住址
  16. private String enrol; //入学时间
  17. //private int fid; //外键 家庭
  18. //private int tid; //外键 老师
  19. //构造器(无参构造器必须有)/set/get/toString 你们补充一下
  20. }
  21.  
  22. /////////// Mapper
  23. //此注解org.apache.ibatis.annotations.Mapper 是mybatis提供的加入容器
  24. //Mapper 可以说等于 @Component、@Repository、@Server、@Controller
  25. @Mapper
  26. public interface StudentMapper {
  27. //查询全部
  28. @Select("select * from student")
  29. @Results(id = "studentMapper", value = {
  30. @Result(id = true, column = "sid", property = "id"),
  31. @Result(column = "sname", property = "name"),
  32. @Result(column = "ssex", property = "sex"),
  33. @Result(column = "sage", property = "age"),
  34. @Result(column = "scredit", property = "credit"),
  35. @Result(column = "smoney", property = "money"),
  36. @Result(column = "saddress", property = "address"),
  37. @Result(column = "senrol", property = "enrol")
  38. })
  39. List<Student> findAll();
  40. }
  41.  
  42. ///////////Service
  43. /**
  44. * @author: xiaofeng
  45. * @date: Create in $DATE
  46. * @description: 学生业务接口
  47. * @version: v1.0.0
  48. */
  49. public interface StudentService {
  50. //查询全部
  51. List<Student> findAll();
  52. }
  53. /**
  54. * @author: xiaofeng
  55. * @date: Create in $DATE
  56. * @description: 学生业务实现
  57. * @version: v1.0.0
  58. */
  59. @Service //注入到容器
  60. public class StudentServiceImpl implements StudentService {
  61.  
  62. //注入对象 如果是IDEA编译器这边会有个红线错误,不影响
  63. @Autowired
  64. private StudentMapper studentMapper;
  65.  
  66. //查询全部
  67. @Override
  68. public List<Student> findAll() {
  69. return studentMapper.findAll();
  70. }
  71. }
  72.  
  73. //////////Controller
  74. @RestController
  75. @RequestMapping("/student")
  76. public class StudentController {
  77.  
  78. @Autowired
  79. private StudentService studentService;
  80.  
  81. @RequestMapping("/findAll")
  82. public List<Student> findAll() {
  83. System.out.println("访问成功");
  84. //这里通过json把对象写到浏览器,要序列化对象
  85. return studentService.findAll();
  86. }
  87. }

POJO、Mapper、Service、Controller文件

注:使用http://localhost:8080/student/findAll访问,还有就是Mapper文件夹里面的代码一定要写在主函数类当前包及其子包下,如果不在则需要在入口类添加@MapperScan或者@MapperScans注解扫描一下,这个是mybatis提供的

(2):使用Mapper.xml映射完成集成

  1. spring:
  2. datasource:
  3. driver-class-name: com.mysql.cj.jdbc.Driver
  4. url: jdbc:mysql://127.0.0.1:3306/demo_school?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
  5. username: root
  6. password: 123
  7.  
  8. # spring继承mybatis环境
  9. # type-aliases-package:pojo别名扫描包
  10. # mapper-locations:加载mybatis映射文件
  11. mybatis:
  12. type-aliases-package: cn.xw.pojo
  13. mapper-locations: classpath:mapper/*Mapper.xml
  14.  
  15. # 加上 ?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC 是为了防止SpringBoot报时区错误
  16. # com.mysql.jdbc.Driver 这种的已经过时了,但是不代表就剔除了 可以用

更改application.yml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="cn.xw.mapper.StudentMapper">
  6. <!--名称字段不一样可以使用这个映射名称对应-->
  7. <resultMap id="studentMapper" type="student">
  8. <id column="sid" property="id"/>
  9. <result column="sname" property="name"/>
  10. <result column="ssex" property="sex"/>
  11. <result column="sage" property="age"/>
  12. <result column="sscore" property="credit"/>
  13. <result column="smoney" property="money"/>
  14. <result column="saddress" property="address"/>
  15. <result column="senrol" property="enrol"/>
  16. </resultMap>
  17. <!--查询全部学生 要使用上面的resultMap才可以-->
  18. <select id="findAll" resultMap="studentMapper">
  19. select * from student;
  20. </select>
  21. </mapper>

在resources下创建mapper/StudentMapper.xml

删除之前在Mapper使用注解的SQL语句删除,只留方法

2:Spring Boot 集成 Redis

  springBoot集成Redis后,以上个案例的基础上做个查询学生缓存,如果第一次查询则缓存到redis服务器里,然后从redis读取数据返回到客户端

  1. <!--导入redis启动器-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. </dependency>

  1. @RestController
  2. @RequestMapping("/student")
  3. public class StudentController {
  4.  
  5. @Autowired
  6. private StudentService studentService;
  7.  
  8. //注入redis模板对象
  9. @Autowired
  10. private RedisTemplate redisTemplate;
  11.  
  12. @RequestMapping("/findAll")
  13. public List<Student> findAll() {
  14. System.out.println("访问成功");
  15.  
  16. //获取类名
  17. String className = studentService.getClass().getName();
  18.  
  19. //以类名+方法名的方式作为key来查询redis缓存数据
  20. List<Student> studentList = (List<Student>) redisTemplate.boundValueOps(className + "findAll").get();
  21. //redis没有数据 查询数据库放入到redis
  22. if (studentList == null) {
  23. System.out.println("从数据库查询数据放入到redis");
  24. //查询数据库
  25. studentList = studentService.findAll();
  26. //把查询到的数据放入redis中 key为类名加findAll
  27. redisTemplate.boundValueOps(className + "findAll").set(studentList);
  28. } else {
  29. System.out.println("从redis读取数据缓存");
  30. }
  31. //这里通过json把对象写到浏览器,要序列化对象
  32. return studentList;
  33. }
  34. }

更改StudentController

3:Spring Boot 集成定时器

    使用SpringBoot完成一个简易的定时器,每5秒输出一下当前的时间到控制台;

  首先在入口函数类上面加@EnableScheduling注解,代表开启定时器

  1. @Component
  2. public class TimerUtil {
  3. /**
  4. * @Scheduled 设置方法执行规则 就是定时任务设置
  5. * cron: 设置一个String类型的cron表达式 这个属性和下面6个不要混用
  6. * fixedDelay 以一个固定的延迟时间,上个任务完成后多久执行下一个任务
  7. * fixedDelayString 和上面一样字符串形式传值
  8. * fixedRate 以一个固定的频率运行,不管上一个任务执行时间
  9. * fixedRateString 和上面一样字符串形式传值
  10. * initialDelay 当项目初始化后多久触发事务的执行
  11. * initialDelayString 和上面一样字符串形式传值
  12. */
  13. //使用cron表达式
  14. @Scheduled(initialDelay=10000,fixedDelay = 5000)
  15. public void myTask(){
  16. System.out.println("当前时间:"+new Date());
  17. }
  18. }
  19. //注:写在入口函数类可扫描的范围包下

编写定时器类

4:Spring Boot 集成Test单元测试

  1. <!--测试启动start-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-test</artifactId>
  5. <scope>test</scope>
  6. </dependency>
  1. //@RunWith(SpringRunner.class) 在老版的SpringBoot项目需要这个
    //2.2.0.RELEASE以后,springboot测试类不再需要@Runwith的注解

  2. @SpringBootTest //注明为SpringBoot测试类
  3. class DemomybatissApplicationTests {
  4. //注入StudentService对象
  5. @Autowired
  6. private StudentService studentService;
  7. @Test
  8. void contextLoads() {
  9. System.out.println(studentService.findAll());
  10. }
  11. }

5:Spring Boot 发送HTTP请求

  要在SpringBoot内部发送HTTP请求就得用到RestTemplate模板,它是Rest的HTTP客户端模板工具类;对基于HTTP客户端进行了封装;还实现了对象与JSON的序列化与反序列化;不限定客户端类型,目前常用的3种客户端都支持:HttpClient、OKHttp、JDK原生URLConnection(默认方式)

  1. @SpringBootApplication
  2. @EnableScheduling //开启定时器注解
  3. public class DemomybatissApplication {
  4.  
  5. public static void main(String[] args) {
  6. SpringApplication.run(DemomybatissApplication.class, args);
  7. }
  8. //注册RestTemplate对象放入IOC容器
  9. @Bean
  10. public RestTemplate restTemplate(){
  11. return new RestTemplate();
  12. }
  13. }

入口函数类更改

  1. //@RunWith(SpringRunner.class) 在老版的SpringBoot项目需要这个
  2. @SpringBootTest //注明为SpringBoot测试类
  3. class DemomybatissApplicationTests {
  4.  
  5. //注入RestTemplate对象
  6. @Autowired
  7. private RestTemplate restTemplate;
  8.  
  9. @Test
  10. void contextLoads() {
  11. //String.class代表以字符串形式接收结果
  12. String forObject = restTemplate.getForObject("http://baidu.com", String.class);
  13. System.out.println(forObject);
  14. //打印
  15. //<html>
  16. //<meta http-equiv="refresh" content="0;url=http://www.baidu.com/">
  17. //</html>
  18. }
  19. }

编写RestTemplate发送Http请求测试类

6:扩展

  SpringBoot除了上面几个集成外还集成 MongoDB、ElasticSearch、Memcached、邮件服务:普通邮件、模板邮件、验证码、带Html的邮件、RabbitMQ消息中间件、Freemarker或者Thymeleaf等等

六:SpringBoot打包部署

   启动方式有两种,一种是打成jar直接执行,另一种是打包成war包放到Tomcat服务下,启动Tomcat

1:打成Jar包部署运行

  注:pom文件里的<packaging>jar</packaging>必须为jar,默认就是jar

  1. /**
  2. * 第一步:使用IDEA工具把写的代码通过maven的package打包
  3. * 第二步:找到打包后的target文件夹里面,把xxx.jar包扔给测试
  4. * 第三步:自己测试的话使用cmd执行下面命令,前提得检查自己的pom.xml文件中是否有springboot的maven插件
  5. * java -jar xxxx.jar
  6. * 补充:在运行的时候传递参数 通过main函数的args接收
  7. * java -jar xxxx.jar --server.port=8888
  8. * 补充:在运行的时候配置jvm参数,使占用更少的内存
  9. * java -Xmx80m -Xms20m -jar xxxx.jar
  10. */

2:打成War包部署运行

  注:pom文件里的<packaging>war</packaging>必须为jar,默认就是war

  1. 创建一个类如:ServletInitializer.java,继承 SpringBootServletInitializer ,覆盖 configure(),
  2. 把启动类 Application 注册进去。外部 Web 应用服务器构建 Web Application Context 的时候,
  3. 会把启动类添加进去。
  4.  
  5. //如下代码创建的类 除了类名和注册的启动类不一样,其它是固定写法
  6. //WEB-INF/web.xml
  7. public class ServletInitializer extends SpringBootServletInitializer {
  8. @Override
  9. protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
  10. //DemoApplication是自己当前项目的主函数
  11. return builder.sources(DemoApplication.class);
  12. }
  13. }

七:SpringBoot热部署

  我们在之前每次写完代码之后都要重新部署运行,这样特别浪费时间,其实SpringBoot是支持热部署的,但是我们得有相对应的参数配置,导入坐标

  1. 检查当前的pom.xml必须有此配置才可以,然后正常启动运行即可
    <!--工具 用于设置热部署,optional必须为true-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-devtools</artifactId>
  5. <scope>runtime</scope>
  6. <optional>true</optional>
  7. </dependency>

当我们的代码写文运行后,后期更改了代码无需重写部署,只需要按CTRL+F9(Build Project),这是快速构建项目,或点击有上角的锤子;

如果还觉得麻烦,那就设置,一旦更改代码,IDEA失去焦点就自动构建代码,我们要设置一下IDEA配置

八:SpringBoot配置文件深入

1:多环境配置文件

  我们在开发Spring Boot应用时,通常同一套程序会被安装到不同环境,比如:开发dev、测试test、生产pro等。其中数据库地址、服务器端口等等配置都不同,如果每次打包时,都要修改配置文件,那么非常麻烦。profile功能就是来进行动态配置切换的。

(1):单文件的多环境配置

  1. # 在只有application.yml一个文件下配置多个配置环境就需要使用 " --- " 分隔界限
  2. # 为了规范 Dev为开发 Test为测试 Pro为生产
  3. # 配置完以后在这里选择要使用的配置环境
  4. spring:
  5. profiles:
  6. # 开启哪个环境下的配置文件
  7. active: oo
  8. # 引用包含哪个配置文件
  9. include: global
  10.  
  11. # 开发环境配置 Dev
  12. ---
  13. server.port: 8881
  14. # 设置当前的配置界限为 dev开发环境
  15. spring.profiles: dev
  16.  
  17. # 测试环境配置 Test
  18. ---
  19. server.port: 8882
  20. spring.profiles: test
  21.  
  22. # 生产上线环境配置 Pro
  23. ---
  24. server.port: 80
  25. spring.profiles: pro
  26.  
  27. # 全局的配置供include包含使用
  28. ---
  29. server.servlet.context-path: /littleBird
  30. spring.profiles: global

单个application.yml配置文件完成多环境配置  不推荐

(2):多文件的多环境配置 

  1. application.yml 主配置文件(必须有)
  2. # 为了规范 Dev为开发 Test为测试 Pro为生产
  3. # 配置完以后在这里选择要使用的配置环境
  4. spring:
  5. profiles:
  6. # 开启哪个环境下的配置文件
  7. active: dev
  8. # 引入包含共有配置
  9. include: common
  10.  
  11. application-dev.yml/properties 开发环境配置
  12. # 开发环境
  13. server.port: 8881
  14.  
  15. application-test.yml/properties 测试环境配置
  16. # 测试环境
  17. server.port: 8882
  18.  
  19. application-pro.yml/properties 生产环境配置
  20. # 上线环境
  21. server.port: 80
  22.  
  23. application-common.yml/properties 公共环境配置
  24. # 公共配置 供其包含导入
  25. server.servlet.context-path: /littleBird

多文件配置多环境 推荐

(3):profile激活方式

  在上面我介绍了使用配置文件来指定配置环境:spring.profiles.active=xx;可是这个是有局限性的,除了这种方式激活还要另外2种

  1. 配置文件: 再配置文件中配置:spring.profiles.active=dev
  2. 虚拟机参数:VM options 指定:-Dspring.profiles.active=dev
  3. 命令行参数:java jar xxx.jar --spring.profiles.active=dev
    优先级:命令行参数 > 虚拟机参数 > 配置文件

2:松散绑定

  不论配置文件中的属性值是短横线、驼峰式还是下换线分隔配置方式,在注入配置时都可以通过短横线方式取出值;使用范围:properties文件、YAML文件、系统属性

  1. 命名各种方式的名称 application.yml文件下定义方式
  2. # 短横线分隔
  3. parameter1:
  4. spring-boot:
  5. student-name: zhangsan
  6. # 驼峰式
  7. parameter2:
  8. springBoot:
  9. studentName: lisi
  10. # 下划线分隔
  11. parameter3:
  12. spring_boot:
  13. student_name: wangwu
  14.  
  15. 命名各种方式的名称 application.properties文件下定义方式
  16. # 短横线分隔
  17. parameter1.spring-boot.student-name=zhangsan
  18. # 驼峰式
  19. parameter2.springBoot.studentName=lisi
  20. # 下划线分隔
  21. parameter3.spring_boot.student_name: wangwu
  22.  
  23. 取出方式:使用短横线分隔可以取出上面的任意一直格式
  24. 注:在@Value获取上面的3种方式命名的配置只能使用短横线分隔通配
  25. 否则配置文件写啥名,获取就写啥名,一一对应
  26. @Value(value="${parameter1.spring-boot.student-name}")
  27. @Value(value="${parameter2.spring-boot.student-name}")
  28. @Value(value="${parameter3.spring-boot.student-name}")

松散绑定配置文件介绍

3:配置路径及其加载顺序

4:外部配置加载顺序  官方文档

  外部加载顺序就是说在程序运行时加载外部的配置信息的顺序,如我们常用的命令行下指定额外信息 java -jar  xxx.jar --server.port=8888

  1. # 这个是2.1.11版本的springboot之前的信息,中文的看的清楚,以具体版本为准
  2. 1:开启 DevTools 时, ~/.spring-boot-devtools.properties
  3. 2:测试类上的 @TestPropertySource 注解
  4. 3@SpringBootTest#properties 属性
  5. 4:==命令?参数(--server.port=9000 )==
  6. 5SPRING_APPLICATION_JSON 中的属性
  7. 6ServletConfig 初始化参数
  8. 7ServletContext 初始化参数
  9. 8java:comp/env 中的 JNDI 属性
  10. 9System.getProperties()
  11. 10:操作系统环境变量
  12. 11random.* 涉及到的 RandomValuePropertySource
  13. 12jar 包外部的 application-{profile}.properties .yml
  14. 13jar 包内部的 application-{profile}.properties .yml
  15. 14jar 包外部的 application.properties .yml
  16. 15jar 包内部的 application.properties .yml
  17. 16@Configuration 类上的 @PropertySource
  18. 17SpringApplication.setDefaultProperties() 设置的默认属性

中文介绍

5:修改配置文件位置及默认名称

  我们知道配置文件只能以application.yml/properties来定义,但是名称不一样是可以指定具体文件名,也可以把配置文件放入其它位置并指定都是可以的;指定的方式我以cmd下指定参数 java -jar xxx.jar  --xxx  -xxx 方式指定,或在IDEA里面指定-xxx参数

  1. # 自定义配置文件名称
  2. --spring.config.name=myApplication
  3. # 指定配置文件存储位置 或 指定配置文件存储位置及配置文件名称
    --spring.config.location=classpath:/myconfig/myApplication.yml
    注:多个配置参数以空格隔开 --xxx -xxx

九:SpringBoot监听器

  我们知道JavaEE包括13门规范,其中Servlet规范包括三个技术点:Servlet、Listener、Filter;而本章介绍的是监听器,监听器就是监听某个对象的状态变化;SpringBoot中的监听器有很多种:如下

  1. ①:CommandLineRunner 应用程序启动完成后
  2. ②:ApplicationRunner 应用程序启动完成后
  3.  
  4. ③:ApplicationContextInitializer 程序运行初始化前
  5. ④:SpringApplicationRunListener 多功能监听器

1:对开发者有益的监听器

  1. @Component //实现CommandLineRunner接口的监听器必须要加入IOC容器
  2. public class MyCommandLineRunner implements CommandLineRunner {
  3. //注 参数args是主函数入口的args传来的
  4. @Override
  5. public void run(String... args) throws Exception {
  6. System.out.println("应用程序启动完成后 打印:CommandLineRunner");
  7. }
  8. }

CommandLineRunner 监听器使用

  1. @Component //实现ApplicationRunner接口的监听器必须要加入IOC容器
  2. public class MyApplicationRunner implements ApplicationRunner {
  3.  
  4. //注 参数args是主函数入口的args传来的
  5. @Override
  6. public void run(ApplicationArguments args) throws Exception {
  7. System.out.println("应用程序启动完成后 打印:ApplicationRunner");
  8. }
  9. }

ApplicationRunner 监听器使用

2:对框架开发者有意义的监听器 功能多

  1. public class MyApplicationContextInitializer implements ApplicationContextInitializer {
  2. @Override
  3. public void initialize(ConfigurableApplicationContext applicationContext) {
  4. System.out.println("程序运行初始化前 打印:ApplicationContextInitializer");
  5. }
  6. }

ApplicationContextInitializer 监听器使用

  1. public class MySpringApplicationRunListener implements SpringApplicationRunListener {
  2. //注意:此构造方法必须要写 不写就给你报个错误
  3. public MySpringApplicationRunListener(SpringApplication application, String[] args) {}
  4. @Override
  5. public void starting(ConfigurableBootstrapContext bootstrapContext) {
  6. System.out.println("应用程序开始启动==>starting");
  7. }
  8. @Override
  9. public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
  10. System.out.println("环境准备完成==>environmentPrepared");
  11. }
  12. @Override
  13. public void contextPrepared(ConfigurableApplicationContext context) {
  14. System.out.println("Spring容器准备完成==>contextPrepared");
  15. }
  16. @Override
  17. public void contextLoaded(ConfigurableApplicationContext context) {
  18. System.out.println("Spring容器加载完成==>contextLoaded");
  19. }
  20. @Override
  21. public void started(ConfigurableApplicationContext context) {
  22. System.out.println("应用程序启动完成==>started");
  23. }
  24. //注:running成功与failed异常只会存在一个
  25. @Override
  26. public void running(ConfigurableApplicationContext context) {
  27. System.out.println("应用程序开始运行==>running");
  28. }
  29. @Override
  30. public void failed(ConfigurableApplicationContext context, Throwable exception) {
  31. System.out.println("应用程序运行时抛出异常==>failed");
  32. }
  33. }

SpringApplicationRunListener 监听器使用

  1. # 说明 在resources目录下创建META-INF文件夹 并在里面创建一个spring.factories
  2. # 主要目的是解耦:将监听器的配置权交给第三方厂商、插件开发者
  3. # 框架提供接口,实现类由你自己来写,释放原生API能力,增加可定制性
  4. # META-INF/spring.factories文件中配置接口的实现类名称
  5.  
  6. # 配置ApplicationContextInitializer监听器的配置
  7. # 左边监听器的全路径名称=右边实现此监听器的全路径名
  8. org.springframework.context.ApplicationContextInitializer=cn.xw.lintener.MyApplicationContextInitializer
  9. # 配置SpringApplicationRunListener监听器的配置
  10. # 左边监听器的全路径名称=右边实现此监听器的全路径名
  11. org.springframework.boot.SpringApplicationRunListener=cn.xw.lintener.MySpringApplicationRunListener

使用ApplicationContextInitializer/SpringApplicationRunListener监听器必看 配置一些信息才可使用

十:自动配置实现分析

  我们在导入spring-boot-starter-web启动器无需其它配置就可以之间用,还有我们导入spring-boot-starter-data-redis启动器后可以直接使用@Autowired直接注入RedisTemplate对象,很奇怪吧,这就是SpringBoot自动配置特性,在下几节我慢慢引入

1:@Import注解进阶

  当我们需要导入某个类到spring容器中去,但spring恰好无法扫描到这个类,而我们又无法修改这个类(jar包形式)。我们就可以通过@import(xxx.class)是将这个类导入到spring容器中

(1):直接导入

  1. //配置类 springConfig
  2. @Configuration
  3. @Import(value={DateConfig.class}) //直接导入
  4. public class SpringConfig { }
  5.  
  6. //普通类,里面有个@Bean注入方法 DateConfig
  7. //被任何一个配置类引用,当前自己类也变为子配置类
  8. public class DateConfig {
  9. //创建时间对象放入容器
  10. @Bean
  11. public Date createDate() { return new Date(); }
  12. }

(2):通过配置类导入

  1. @Configuration
  2. public class SpringConfig {
  3. //创建时间对象放入容器
  4. @Bean
  5. public Date createDate() { return new Date(); }
  6. }
  7.  
  8. @SpringBootApplication
  9. @Import(value={SpringConfig.class}) //导入配置类
  10. public class LintenerDemoApplication {
  11.  
  12. public static void main(String[] args) {
  13. ConfigurableApplicationContext run = SpringApplication.run(LintenerDemoApplication.class, args);
  14. //打印时间对象
  15. System.out.println(run.getBean(Date.class));
  16. }
  17. }

(3):通过ImportSelector接口实现类导入  高级方式

  1. //普通类 里面有个@Bean注入对象
  2. public class DateConfig {
  3. //创建时间对象放入容器
  4. @Bean
  5. public Date createDate() { return new Date(); }
  6. }
  7.  
  8. //创建一个类实现ImportSelector
  9. public class MyImportSelector implements ImportSelector {
  10. //这个方法是返回配置类的全类名,导入多少都行,最后通过@Import导入
  11. @Override
  12. public String[] selectImports(AnnotationMetadata importingClassMetadata) {
  13. //返回一个数组
  14. return new String[]{"cn.xw.config.DateConfig"};
  15. }
  16. }
  17.  
  18. @SpringBootApplication
  19. @Import(value={MyImportSelector.class}) //导入配置类
  20. public class LintenerDemoApplication {
  21.  
  22. public static void main(String[] args) {
  23. ConfigurableApplicationContext run = SpringApplication.run(LintenerDemoApplication.class, args);
  24. //打印时间对象
  25. System.out.println(run.getBean(Date.class));
  26. }
  27. }

使用ImportSelector接口

2:@Configuration注解进阶

  相对这个注解大家肯定不陌生,只要是Spring注解配置类都有这玩意;其实只要添加@Configuration注解的类里面可以衍生出各种条件注解供我们使用,前提只能在注解类下使用,它就是@Conditional条件注解,这个条件注解又衍生出各种详细的条件注解

注:@EnableAutoConfiguration 其本质是 @Import 和 @Configuration的组合

  1. 一:class类条件
  2. @ConditionalOnClass == 存在指定类条件
  3. @ConditionalOnMissingClass == 不存在指定类条件
  4. 二:属性条件
  5. @ConditionalOnProperty == 属性条件,还可以为属性设置默认值
  6. 三:Bean条件
  7. @ConditionalOnBean == 存在Bean条件
  8. @ConditionalOnMissingBean == 不存在Bean条件
  9. @ConditionalOnSingleCondidate == 只有一个Bean条件
  10. 四:资源条件
  11. @ConditionalResource == 资源条件
  12. 五:Web应用条件
  13. @ConditionalOnWebApplication == web应用程序条件
  14. @ConditionalOnNotWebApplication == 不是web应用程序条件
  15. 六:其他条件
  16. @ConditionalOneExpression == EL表达式条件
  17. @ConditionalOnJava == 在特定的Java版本条件

  @Configuration还有一些加载顺序的方式

  1. 1@AutoConfigureBefore==在那些自动配置之前执行
  2. 2@AutoConfigureAfter==在那些自动配置之后执行
  3. 3@AutoConfigureOrder==自动配置顺序

 (1):@ConditionalOnClass  与 @ConditionalOnProperty 介绍

  1. @ConditionalOnClass注解属性介绍
  2. Class<?>[] value():以类的class形式的数组
  3. String[] name():以类的全路径名的字符串数组
  4.  
  5. @ConditionalOnProperty注解属性介绍
  6. value name:数组,获取对应property名称的值,它们只能存在其中一个
  7. prefix:配置属性名称的前缀,比如spring.http.encoding
  8. havingValue:可与name组合使用,比较获取到的属性值与havingValue给定的值是否相同,相同才加载配置
  9. matchIfMissing:缺少该配置属性时是否可以加载。如果为true,没有该配置属性时也会正常加载;反之则不会生效

  1. //学生类
  2. public class Student {
  3. private String name;
  4. private String identity;
  5. //省略了get/set,
  6. }
  7.  
  8. //老师类
  9. public class Teacher {
  10. private String name;
  11. private String identity;
  12. //省略了get/set,
  13. }
  14.  
  15. //需求,当创建Teacher加入容器时得判断当前是否存在Student这个类
  16. @Configuration
  17. @ConditionalOnClass(name = "cn.xw.pojo.Student")
  18. public class SpringConfig {
  19.  
  20. //可以通过spring.myconfig.enable=true开启 或者false 关闭容器注册
  21. @Bean(value = "teacher")
  22. @ConditionalOnProperty(prefix = "spring.myconfig", name = "enable", havingValue ="true", matchIfMissing = true)
  23. public Teacher createTeacher() {
  24. Teacher teacher = new Teacher();
  25. teacher.setName("张老师");
  26. teacher.setIdentity("老师");
  27. return teacher;
  28. }
  29. }
  30.  
  31. @SpringBootApplication
  32. //导入配置类
  33. @Import(value={SpringConfig.class})
  34. public class LintenerDemoApplication {
  35. public static void main(String[] args) {
  36. ConfigurableApplicationContext run = SpringApplication.run(LintenerDemoApplication.class, args);
  37. //打印时间对象
  38. System.out.println(run.getBean(Teacher.class).getName());
  39. }
  40. }
  41.  
  42. //application.properties
  43. # 关闭容器注册
  44. spring.myconfig.enable=false

案例讲解注解

  1. //注解类
  2. @Configuration(proxyBeanMethods = false)
  3. //条件注解 确保存在RedisOperations类
  4. @ConditionalOnClass(RedisOperations.class)
  5. //@Import 和 @ConfigurationProperties结合 RedisProperties类就是我们配置额外变量的spring.redis
  6. @EnableConfigurationProperties(RedisProperties.class)
  7. //导入配置类
  8. @Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
  9. public class RedisAutoConfiguration {
  10.  
  11. @Bean
  12. //判断不存在redisTemplate的Bean条件
  13. @ConditionalOnMissingBean(name = "redisTemplate")
  14. //判断只有一个RedisConnectionFactory的Bean条件
  15. @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
  16. public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
  17. RedisTemplate<Object, Object> template = new RedisTemplate<>();
  18. template.setConnectionFactory(redisConnectionFactory);
  19. return template;
  20. }
  21.  
  22. //下面差不多
  23. @Bean
  24. @ConditionalOnMissingBean
  25. @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
  26. public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
  27. StringRedisTemplate template = new StringRedisTemplate();
  28. template.setConnectionFactory(redisConnectionFactory);
  29. return template;
  30. }
  31. }

RedisTemplate自动注入分析

十一:自定义auto-Configuration及starter

  我们平常导入是第三方mybatis-spring-boot-starter启动器都是由第三方提供给,特点就是以mybatis开头,那下面我们自定义starter也得是自定义名称开头,我们要自定义auto-Configuraction并使用必备的四个角色功能主体框架、自动配置模块、starter模块、开发者引用

  1. 1:定制自动配置必要内容
  2. autoconfiguration模块,包含自动配置代码。自定义 *-spring-boot-autoconfigure
  3. starter模块。自定义 *-spring-boot-starter
  4. 2:自动配置命名方式
  5. 官方的Starters
  6. spring-boot-starter-* 如:spring-boot-starter-web
  7. 非官方的starters
  8. *-spring-boot-starter 如:mybatis-spring-boot-starter
  9. 3SpringBoot起步依赖,Starter Dependencies

  接下来我要创建一个第三方模块,功能主体模块是一个图形打印模块,根据配置文件的不同打印出不同的图案,还要就是一个自动配置模块和starter模块咯,最后由我来在普通的springboot应用中调用这个自定义的自动配置

(1):功能主体模块

  1. 主体功能模块maven坐标
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <project xmlns="http://maven.apache.org/POM/4.0.0"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  6. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  7. <modelVersion>4.0.0</modelVersion>
  8. <groupId>cn.tx</groupId>
  9. <artifactId>graphic-printing</artifactId>
  10. <version>1.0-SNAPSHOT</version>
  11. <!--设置maven使用什么版本的jdk解析编译-->
  12. <properties>
  13. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  14. <maven.compiler.source>1.8</maven.compiler.source>
  15. <maven.compiler.target>1.8</maven.compiler.target>
  16. </properties>
  17. </project>
  18. 主体功能模块具体类方法
  19. //图形打印对象
  20. public class GraphicPrintingUtil {
  21. private Integer width = 4;
  22. private Integer height = 3;
  23. //别忘了添加get/set方法,后面会参数注入
  24.  
  25. //打印图形 方法
  26. public void graphicPrinting() {
  27. System.out.println(">图形开始打印<");
  28. for (int i = 1; i <= height; i++) {
  29. for (int j = 1; j <= width; j++) {
  30. System.out.print(" * ");
  31. }
  32. System.out.println();
  33. }
  34. }
  35. }

功能主体代码 模块名:graphic-printing

(2):自动配置模块

  1. 自动配置模块maven坐标
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <project xmlns="http://maven.apache.org/POM/4.0.0"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  6. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  7. <modelVersion>4.0.0</modelVersion>
  8. <!--导入Springboot父坐标-->
  9. <parent>
  10. <artifactId>spring-boot-starter-parent</artifactId>
  11. <groupId>org.springframework.boot</groupId>
  12. <version>2.4.1</version>
  13. </parent>
  14. <!--当前本项目的一些信息-->
  15. <groupId>cn.tx</groupId>
  16. <artifactId>graphic-spring-boot-autoconfigure</artifactId>
  17. <version>1.0-SNAPSHOT</version>
  18. <!--坐标-->
  19. <dependencies>
  20. <!--导入SpringBoot的自动配置坐标 因为代码中要写配置注解-->
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-autoconfigure</artifactId>
  24. </dependency>
  25. <!--导入我们之前创建的主体模块graphic-printing-->
  26. <dependency>
  27. <groupId>cn.tx</groupId>
  28. <artifactId>graphic-printing</artifactId>
  29. <version>1.0-SNAPSHOT</version>
  30. </dependency>
  31. </dependencies>
  32. </project>
  33. 自动配置模块具体类方法
  34. ## GraphicConfiguration类
  35. @Configuration //注解类
  36. @Import(value = {GraphicProperties.class}) //导入配置类
  37. @ConditionalOnClass(GraphicPrintingUtil.class)//判断当前项目是否存在GraphicPrintingUtil类
  38. public class GraphicConfiguration {
  39. @Bean
  40. @ConditionalOnProperty(prefix = "graphic.printing", name = "enable", havingValue = "true", matchIfMissing = true)
  41. //@ConfigurationProperties(prefix = "graphic.config") 可以使用此注解直接注入 注入时值可有可无
  42. public GraphicPrintingUtil createGraphicPrintingUtil(GraphicProperties g) {
  43. //创建图形打印对象,主体模块上的对象
  44. GraphicPrintingUtil printingUtil = new GraphicPrintingUtil();
  45. //设置宽高
  46. printingUtil.setHeight(g.getHeight());
  47. printingUtil.setWidth(g.getWidth());
  48. return printingUtil;
  49. }
  50. }
  51.  
  52. ## GraphicProperties 配置类
  53. //这里报红不管他,后面使用者导入<artifactId>spring-boot-configuration-processor</artifactId>
  54. @ConfigurationProperties(prefix = "graphic.config")
  55. public class GraphicProperties {
  56. private Integer width;
  57. private Integer height;
  58. //别忘了写get/set
  59. }

自动配置代码 模块名:graphic-spring-boot-autoconfigure

  1. # 注册自定义自动配置
  2. # 前面是固定的,后面是自定义配置类
  3. org.springframework.boot.autoconfigure.EnableAutoConfiguration=cn.tx.config.GraphicConfiguration

在resources下创建META-INF文件夹,并在下面创建spring.factories配置

(3):stater模块

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <!--自己项目坐标-->
  8. <groupId>cn.tx</groupId>
  9. <artifactId>graphic-spring-boot-starter</artifactId>
  10. <version>1.0-SNAPSHOT</version>
  11. <dependencies>
  12. <!--主体功能模块-->
  13. <dependency>
  14. <groupId>cn.tx</groupId>
  15. <artifactId>graphic-printing</artifactId>
  16. <version>1.0-SNAPSHOT</version>
  17. </dependency>
  18. <!--自动配置类autoconfigure-->
  19. <dependency>
  20. <groupId>cn.tx</groupId>
  21. <artifactId>graphic-spring-boot-autoconfigure</artifactId>
  22. <version>1.0-SNAPSHOT</version>
  23. </dependency>
  24. </dependencies>
  25. </project>

stater模块 模块名:graphic-spring-boot-starter

  注:此模块啥都不用,只要pom.xml文件即可

(3):开发者引用

  1. 注:此模块和正常SpringBoot一样,可以使用脚手架构建
  2. 使用者maven坐标
  3. <?xml version="1.0" encoding="UTF-8"?>
  4. <project xmlns="http://maven.apache.org/POM/4.0.0"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  6. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  7. https://maven.apache.org/xsd/maven-4.0.0.xsd">
  8. <modelVersion>4.0.0</modelVersion>
  9. <!--springboot父坐标-->
  10. <parent>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-parent</artifactId>
  13. <version>2.4.1</version>
  14. <relativePath/>
  15. </parent>
  16. <!--本项目的坐标信息-->
  17. <groupId>cn.xw</groupId>
  18. <artifactId>test001</artifactId>
  19. <version>0.0.1-SNAPSHOT</version>
  20. <name>test001</name>
  21. <description>Demo project for Spring Boot</description>
  22. <properties>
  23. <java.version>1.8</java.version>
  24. </properties>
  25. <dependencies>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter</artifactId>
  29. </dependency>
  30. <!--导入我们自定义的stater启动器-->
  31. <dependency>
  32. <groupId>cn.tx</groupId>
  33. <artifactId>graphic-spring-boot-starter</artifactId>
  34. <version>1.0-SNAPSHOT</version>
  35. </dependency>
  36. <!--一定要导入,是为了注入配置文件里面的数值-->
  37. <dependency>
  38. <groupId>org.springframework.boot</groupId>
  39. <artifactId>spring-boot-configuration-processor</artifactId>
  40. <optional>true</optional>
  41. </dependency>
  42. </dependencies>
  43. <!--maven插件-->
  44. <build>
  45. <plugins>
  46. <plugin>
  47. <groupId>org.springframework.boot</groupId>
  48. <artifactId>spring-boot-maven-plugin</artifactId>
  49. </plugin>
  50. </plugins>
  51. </build>
  52. </project>
  53. 使用者具体类方法
  54. @SpringBootApplication
  55. public class Test001Application {
  56. public static void main(String[] args) {
  57. ConfigurableApplicationContext run = SpringApplication.run(Test001Application.class, args);
  58. //ConfigurableApplicationContext是ClassPathXmlApplicationContext子类
  59. run.getBean(GraphicPrintingUtil.class).graphicPrinting();
  60. }
  61. }
  62. 配置文件application.properties
  63. graphic.printing.enable=true
  64. graphic.config.width=10
  65. graphic.config.height=15

开发者模块 模块名:test001

十二:切换内置web应用服务器

  1. SpringBootweb环境中默认使用tomcat作为内置服务器,其实还提供了另外2种内置服务器供我们选择,我们可以很方便的进行切换。
  2. 1Tomcat:这个是使用最广泛但性能不太好的web应用服务器 默认
  3. 2JettyJetty 是一个开源的servlet容器,它为基于Javaweb容器,例如JSPservlet提供运行环境。
  4. 3Undertow 是红帽公司开发的一款基于 NIO 的高性能 Web 嵌入式服务器

  Tomcat方式:Tomcat started on port(s): 8080 (http) with context path ''
  Jetty方式:Jetty started on port(s) 8080 (http/1.1) with context path '/'
  Undertow方式:Undertow started on port(s) 8080 (http)

  1. <!--导入web的starter启动器-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. <!--一定要排除tomcat的starter 因为默认就是tomcat-->
  6. <exclusions>
  7. <exclusion>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-tomcat</artifactId>
  10. </exclusion>
  11. </exclusions>
  12. </dependency>
  13. <!--导入jetty容器依赖-->
  14. <dependency>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-jetty</artifactId>
  17. </dependency>

切换为Jetty

  1. <!--导入web的starter启动器-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. <!--一定要排除tomcat的starter 因为默认就是tomcat-->
  6. <exclusions>
  7. <exclusion>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-tomcat</artifactId>
  10. </exclusion>
  11. </exclusions>
  12. </dependency>
  13. <!--导入undertow容器依赖-->
  14. <dependency>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-undertow</artifactId>
  17. </dependency>

切换Undertow

十三:SpringBoot生产级监控

  SpringBoot自带监控功能Actuator,可以帮助实现对程序内部运行情况监控,比如监控状况、Bean加载情况、配置属性、日志信息等

1:项目集成Actuator监控服务

  其实导入健康服务特别简单,任何一个SpringBoot只需要加入一个监控启动器则可开启监控服务,然后项目正常运行即可

  1. <!--监控服务Actuator启动器-->
    <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-actuator</artifactId>
  4. </dependency>

  保存SpringBoot导入监控坐标后启动程序,在程序运行的情况下访问 http://localhost:8080/actuator 则可监控程序

 补充:默认只可以监控这几项,其实可以监测很多模块

  1. 路径 描述 默认开启
  2. /beans 显示容器的全部的Bean,以及它们的关系 N
  3. /env 获取全部环境属性 N
  4. /env/{name} 根据名称获取特定的环境属性值 N
  5. /health 显示健康检查信息 Y
  6. /info 显示设置好的应用信息 Y
  7. /mappings 显示所有的@RequestMapping信息 N
  8. /metrics 显示应用的度量信息 N
  9. /scheduledtasks 显示任务调度信息 N
  10. /httptrace 显示Http Trace信息 N
  11. /caches 显示应用中的缓存 N
  12. /conditions 显示配置条件的匹配情况 N
  13. /configprops 显示@ConfigurationProperties的信息 N
  14. /loggers 显示并更新日志配置 N
  15. /shutdown 关闭应用程序 N
  16. /threaddump 执行ThreadDump N
  17. /headdump 返回HeadDump文件,格式为HPROF N
  18. /prometheus 返回可供Prometheus抓取的信息 N

监控应用endpoint

常用application.properties配置

  1. # 暴露所有的监控点
  2. management.endpoints.web.exposure.include=*
  3. # 定义Actuator访问路径
  4. management.endpoints.web.base-path=/act
  5. # 开启endpoint 关闭服务功能 访问关闭路径只能发送post请求才可关闭
  6. management.endpoint.shutdown.enabled=true

33333333333

  • 配置文件: 再配置文件中配置:spring.profiles.active=dev
  • 虚拟机参数:在VM options 指定:-Dspring.profiles.active=dev
  • 命令行参数:java –jar xxx.jar --spring.profiles.active=dev

SpringBoot入门及深入的更多相关文章

  1. SpringBoot入门教程(二)CentOS部署SpringBoot项目从0到1

    在之前的博文<详解intellij idea搭建SpringBoot>介绍了idea搭建SpringBoot的详细过程, 并在<CentOS安装Tomcat>中介绍了Tomca ...

  2. SpringBoot入门基础

    目录 SpringBoot入门 (一) HelloWorld. 2 一 什么是springboot 1 二 入门实例... 1 SpringBoot入门 (二) 属性文件读取... 16 一 自定义属 ...

  3. SpringBoot入门示例

    SpringBoot入门Demo SpringBoot可以说是Spring的简化版.配置简单.使用方便.主要有以下几种特点: 创建独立的Spring应用程序 嵌入的Tomcat,无需部署WAR文件 简 ...

  4. Spring全家桶系列–[SpringBoot入门到跑路]

    //本文作者:cuifuan Spring全家桶————[SpringBoot入门到跑路] 对于之前的Spring框架的使用,各种配置文件XML.properties一旦出错之后错误难寻,这也是为什么 ...

  5. springboot入门之一:环境搭建(续)

    在上篇博客中从springboot的入门到运行一个springboot项目进行了简单讲述,详情请查看“springboot入门之一”.下面继续对springboot做讲述. 开发springboot测 ...

  6. 【Java】SpringBoot入门学习及基本使用

    SpringBoot入门及基本使用 SpringBoot的介绍我就不多说了,核心的就是"约定大于配置",接下来直接上干货吧! 本文的实例: github-LPCloud,欢迎sta ...

  7. SpringBoot入门(三)——入口类解析

    本文来自网易云社区 上一篇介绍了起步依赖,这篇我们先来看下SpringBoot项目是如何启动的. 入口类 再次观察工程的Maven配置文件,可以看到工程的默认打包方式是jar格式的. <pack ...

  8. SpringBoot入门(五)——自定义配置

    本文来自网易云社区 大部分比萨店也提供某种形式的自动配置.你可以点荤比萨.素比萨.香辣意大利比萨,或者是自动配置比萨中的极品--至尊比萨.在下单时,你并没有指定具体的辅料,你所点的比萨种类决定了所用的 ...

  9. SpringBoot入门(四)——自动配置

    本文来自网易云社区 SpringBoot之所以能够快速构建项目,得益于它的2个新特性,一个是起步依赖前面已经介绍过,另外一个则是自动配置.起步依赖用于降低项目依赖的复杂度,自动配置负责减少人工配置的工 ...

  10. SpringBoot入门(二)——起步依赖

    本文来自网易云社区 在前一篇我们通过简单几步操作就生成了一个可以直接运行的Web程序,这是因为SpringBoot代替我们做了许多工作,概括来讲可以分为起步依赖和自动配置.这一篇先来看看起步依赖. 项 ...

随机推荐

  1. TimSort源码详解

    Python的排序算法由Peter Tim提出,因此称为TimSort.它最先被使用于Python语言,后被多种语言作为默认的排序算法.TimSort实际上可以看作是mergeSort+binaryS ...

  2. django APIview使用

    1.APIview使用 ModelVIewSet 是对 APIView 封装 ModelSerializer 是对 Serializer 1.1 在 user/urls.py 中添加路由 urlpat ...

  3. 11g RAC 集群数据库不能跟随集群启动

    1.查看集群资源详细情况 [oracle@rac01-+ASM1 ~]$ crsctl stat res -p 2.修改集群资源ora.rac.db的auto_start属性改为always [ora ...

  4. Servlet中的装饰者模式

    装饰者模式 Decorator模式或者Wrapper模式允许修饰或者封装(在字面意义中,即修改行为)一个对象,即使你没有该对象的源代码或者该对象标识为final. Decorator模式适用于无法继承 ...

  5. ES6新增数据类型Symbol

    Symbol的含义? ES6(2015) 引入了第七种原始数据类型Symbol,Symbol英文文意思为 符号.象征.标记.记号,在 js 中更确切的翻译应该为独一无二的 Symbol的使用? Sym ...

  6. [日常摸鱼]bzoj1444 [JSOI2009]有趣的游戏——AC自动机+矩阵

    今天学校跳蚤市场摆摊聚众吸毒打call,东西卖了一百多好开心_(:з」∠)_ (然后大家中午就去吃了一顿好的x) 下午听演讲然后现在来填坑orz(其实是昨晚的坑) 题目:bzoj1444 先用字符串构 ...

  7. [OI笔记]杂题整理1(基础篇~)

    算是开学第四周啦,之前的三周大概过了一遍基础图论和数学相关的内容.这篇随笔打算口胡一些近期做感觉比较好的数学相关的题目 因为这段时间主要是看紫书学的,所以其实会有些出自UVA的例题,如果需要题目但是觉 ...

  8. vscode php转到定义

    点击再settings.json 中编辑 添加这一行,内容为php的安装路径

  9. Helm 带你飞

    文章目录 目录 文章目录 在没使用 Helm之前,向 K8S部署应用,我们要依次部署 deployment. svc 等,步骤较繁琐.况且随着很多项目微服务化,复杂的应用在容器中部署以及管理显得较为复 ...

  10. java基础:详解类和对象,类和对象的应用,封装思想,构造方法详解,附练习案列

    1. 类和对象 面向对象和面向过程的思想对比 : 面向过程 :是一种以过程为中心的编程思想,实现功能的每一步,都是自己实现的 面向对象 :是一种以对象为中心的编程思想,通过指挥对象实现具体的功能 1. ...