SpringBoot
本文最后更新于47 天前,其中的信息可能已经过时,如有错误请发送邮件到big_fw@foxmail.com

1、入门案例

SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的初始搭建以及开发过程。

(1)SpringMVC开发流程

①创建工程,并在 pom.xml 配置文件中配置所依赖的坐标

②编写 web3.0 的配置类

③编写 SpringMVC 的配置类

④编写 Controller

从上面的 SpringMVC 程序开发可以看到,前三步都是在搭建环境,而且这三步基本都是固定的。SpringBoot 就是对这三步进行简化了。

(2)SpringBoot快速入门

1)创建新模块,选择 Spring Initializr ,用来创建 SpringBoot 工程,选中 Web,然后勾选 Spring Web

2)简单创建个controller类就可以启动了~~

@RestController
@RequestMapping("/books")
public class BookController {

   @GetMapping("/{id}")
   public String getById(@PathVariable Integer id){
       System.out.println("id ==> "+id);
       return "hello , spring boot!";
  }
}

3)运行 SpringBoot 工程不需要使用本地的 Tomcat 和 插件,只运行项目 com.itheima 包下的 Application 类。

<!--代码之所以能简化,就是因为指定的父工程和 `Spring Web` 依赖实现的。-->
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   
   <!--指定了一个父工程,父工程中的东西在该工程中可以继承过来使用-->
   <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>2.5.0</version>
   </parent>
   <groupId>com.itheima</groupId>
   <artifactId>springboot_01_quickstart</artifactId>
   <version>0.0.1-SNAPSHOT</version>

   <!--JDK 的版本-->
   <properties>
       <java.version>8</java.version>
   </properties>
   
   <dependencies>
       <!--该依赖就是我们在创建 SpringBoot 工程勾选的那个 Spring Web 产生的-->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
       </dependency>
<!--这个是单元测试的依赖,我们现在没有进行单元测试,所以这个依赖现在可以没有-->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-test</artifactId>
           <scope>test</scope>
       </dependency>
   </dependencies>

   <build>
       <plugins>
           <!--这个插件是在打包时需要的,而这里暂时还没有用到-->
           <plugin>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-maven-plugin</artifactId>
           </plugin>
       </plugins>
   </build>
</project>

4)对比 Spring 程序和 SpringBoot 程序。

  • 坐标Spring 程序中的坐标需要自己编写,而且坐标非常多SpringBoot 程序中的坐标是我们在创建工程时进行勾选自动生成的
  • web3.0配置类Spring 程序需要自己编写这个配置类。这个配置类大家之前编写过,肯定感觉很复杂SpringBoot 程序不需要我们自己书写
  • 配置类Spring/SpringMVC 程序的配置类需要自己书写。而 SpringBoot 程序则不需要书写。

==注意:基于Idea的 Spring Initializr 快速构建 SpringBoot 工程时需要联网。==

2、快速启动SpringBoot工程

由于我们在构建 SpringBoot 工程时已经在 pom.xml 中配置了如下插件

<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

所以我们只需要使用 Mavenpackage 指令打包就会在 target 目录下生成对应的 Jar 包。

注意:该插件必须配置,不然打好的 jar 包也是有问题的。

进入 jar 包所在位置,在 命令提示符 中输入如下命令

jar -jar springboot_01_quickstart-0.0.1-SNAPSHOT.jar

3、SpringBoot概述

原始 Spring 环境搭建和开发存在以下问题:

  • 配置繁琐
  • 依赖设置繁琐

SpringBoot 程序优点恰巧就是针对 Spring 的缺点

  • 自动配置。解决 Spring 程序配置繁琐的问题
  • 起步依赖。解决 Spring 程序依赖设置繁琐的问题
  • 辅助功能(内置服务器,…)。我们在启动 SpringBoot 程序时既没有使用本地的 tomcat 也没有使用 tomcat 插件,而是使用 SpringBoot 内置的服务器。

(1)起步依赖

使用 Spring Initializr 方式创建的 Maven 工程的的 pom.xml 配置文件中自动生成了很多包含 starter 的依赖。

1)父工程

父工程中的父工程:

再进入父工程中:

上图中的 properties 标签中定义了各个技术软件依赖的版本,避免了我们在使用不同软件技术时考虑版本的兼容问题。

dependencyManagement 标签是进行依赖版本锁定,但是并没有导入对应的依赖;如果我们工程需要那个依赖只需要引入依赖的 groupidartifactId 不需要定义 version

build 标签中也对插件的版本进行了锁定,如下图:

看完了父工程中 pom.xml 的配置后不难理解我们工程的的依赖为什么都没有配置 version

2)探索依赖父工程

在我们创建的工程中的 pom.xml 中配置了如下依赖:

进入到该依赖,查看 pom.xml 的依赖会发现它引入了如下的依赖:

里面的引入了 spring-webspring-webmvc 的依赖,这就是为什么我们的工程中没有依赖这两个包还能正常使用 springMVC 中的注解的原因。

而依赖 spring-boot-starter-tomcat ,从名字基本能确认内部依赖了 tomcat,所以我们的工程才能正常启动。

  • 使用任意坐标时,仅书写GAV中的G和A,V由SpringBoot提供G:groupidA:artifactIdV:version
  • 如发生坐标错误,再指定version(要小心版本冲突)

3)切换web服务器

tomcat 服务器切换为 jetty 服务器,jettymaven 私服使用的服务器。

<!--切换 `web` 服务器就需要将默认的 `tomcat` 服务器给排除掉 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>

<!-- 引入 `jetty` 服务器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

4、配置文件

1)配置文件格式

SpringBoot 程序如何修改端口呢?SpringBoot 提供了多种属性配置方式

  • application.propertiesserver.port=80
  • application.yml主要)server:
    port: 81
  • application.yamlserver:
    port: 82

==注意:SpringBoot 程序的配置文件名必须是 application ,只是后缀名不同而已。==

2)三种文件的优先级

==application.properties > application.yml > application.yaml==

3)yaml格式

YAML(YAML Ain’t Markup Language),一种数据序列化格式。这种格式的配置文件在近些年已经占有主导地位,那么这种配置文件和前期使用的配置文件是有一些优势的,我们先看之前使用的配置文件。

xml 的格式:

<enterprise>
<name>itcast</name>
<age>16</age>
<tel>4006184000</tel>
</enterprise>

properties 的格式:

enterprise.name=itcast
enterprise.age=16
enterprise.tel=4006184000

yaml 的格式:

enterprise:
name: itcast
age: 16
tel: 4006184000

优点:

  • 容易阅读yaml 类型的配置文件比 xml 类型的配置文件更容易阅读,结构更加清晰
  • 容易与脚本语言交互
  • 以数据为核心,重数据轻格式yaml 更注重数据,而 xml 更注重格式

YAML 文件扩展名:

  • .yml (主流)
  • .yaml

上面两种后缀名都可以,以后使用更多的还是 yml 的。

5、yaml数据的使用

1)示例如下:

com.itheima.controller 包写创建名为 BookController 的控制器,内容如下

@RestController
@RequestMapping("/books")
public class BookController {

@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println("id ==> "+id);
return "hello , spring boot!";
}
}

com.itheima.domain 包下创建一个名为 Enterprise 的实体类等会用来封装数据,内容如下

@RestController
@RequestMapping("/books")
public class BookController {

@Value("${lesson}")
private String lesson;
@Value("${server.port}")
private Integer port;
@Value("${enterprise.subject[0]}")
private String subject_00;

@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(lesson);
System.out.println(port);
System.out.println(subject_00);
return "hello , spring boot!";
}
}

resources 下创建一个名为 application.yml 的配置文件,里面配置了不同的数据,内容如下

lesson: SpringBoot

server:
port: 80

enterprise:
name: itcast
age: 16
tel: 4006184000
subject:
- Java
- 前端
- 大数据

2)Environment对象

上面方式读取到的数据特别零散,SpringBoot 还可以使用 @Autowired 注解注入 Environment 对象的方式读取数据。这种方式 SpringBoot 会将配置文件中所有的数据封装到 Environment 对象中,如果需要使用哪个数据只需要通过调用 Environment 对象的 getProperty(String name) 方法获取。

@RestController
@RequestMapping("/books")
public class BookController {

@Autowired
private Environment env;

@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(env.getProperty("lesson"));
System.out.println(env.getProperty("enterprise.name"));
System.out.println(env.getProperty("enterprise.subject[0]"));
return "hello , spring boot!";
}
}

==注意:这种方式,框架内容大量数据,而在开发中我们很少使用。==

3)自定义对象

SpringBoot 还提供了将配置文件中的数据封装到我们自定义的实体类对象中的方式。

  • 将实体类 bean 的创建交给 Spring 管理。在类上添加 @Component 注解
  • 使用 @ConfigurationProperties 注解表示加载配置文件在该注解中也可以使用 prefix 属性指定只加载指定前缀的数据
  • BookController 中进行注入
@Component
//从配置中读取enterprise属性
@ConfigurationProperties(prefix = "enterprise")
public class Enterprise {
private String name;
private int age;
private String tel;
private String[] subject;

public String getName() {
return name;
}

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

public int getAge() {
return age;
}

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

public String getTel() {
return tel;
}

public void setTel(String tel) {
this.tel = tel;
}

public String[] getSubject() {
return subject;
}

public void setSubject(String[] subject) {
this.subject = subject;
}

@Override
public String toString() {
return "Enterprise{" +
"name='" + name + '\'' +
", age=" + age +
", tel='" + tel + '\'' +
", subject=" + Arrays.toString(subject) +
'}';
}
}

BookController 中自动装配进去,内容如下:

@RestController
@RequestMapping("/books")
public class BookController {

@Autowired
private Enterprise enterprise;

@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(enterprise.getName());
System.out.println(enterprise.getAge());
System.out.println(enterprise.getSubject());
System.out.println(enterprise.getTel());
System.out.println(enterprise.getSubject()[0]);
return "hello , spring boot!";
}
}

使用第三种方式,在实体类上会有警告,这个警告提示解决是在 pom.xml 中添加如下依赖即可

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

6、多环境配置

存在生产,测试,开发环境,为便利切换。

1)yaml配置

application.yml 中使用 --- 来分割不同的配置,内容如下

#设置启用的环境
spring:
profiles:
active: dev

---
#开发
spring:
config:
activate:
on-profile: dev
server:
port: 80
---
#生产
spring:
config:
activate:
on-profile: pro
server:
port: 81
---
#测试
spring:
config:
activate:
on-profile: pro
server:
port: 82
---

2)properties文件(了解)

properties 类型的配置文件配置多环境需要定义不同的配置文件

  • application-dev.properties 是开发环境的配置文件。我们在该文件中配置端口号为 80server.port=80
  • application-test.properties 是测试环境的配置文件。我们在该文件中配置端口号为 81server.port=81
  • application-pro.properties 是生产环境的配置文件。我们在该文件中配置端口号为 82server.port=82

SpringBoot 只会默认加载名为 application.properties 的配置文件,所以需要在 application.properties 配置文件中设置启用哪个配置文件,配置如下:

spring.profiles.active=pro

3)命令行启动

SpringBoot 开发的程序以后都是打成 jar 包,通过 java -jar xxx.jar 的方式启动服务的。

java –jar xxx.jar –-spring.profiles.active=test
java –jar xxx.jar –-server.port=88
java –jar springboot.jar –-server.port=88 –-spring.profiles.active=test

7、配置文件类

resources 下创建一个名为 config 的目录,在该目录中创建 application.yml 配置文件,而在该配置文件中将端口号设置为 81,内容如下

server:
port: 81

而在 resources 下创建的 application.yml 配置文件中并将端口号设置为 80,内容如下

server:
port: 80

运行得出81端口,结论:config下的配置要高于resources。

8、SpringBoot整合junit

1)回顾 Spring 整合 junit

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {

@Autowired
private BookService bookService;

@Test
public void testSave(){
bookService.save();
}
}

2)SpringBoot整合

test/java 下创建 com.itheima 包,在该包下创建测试类,将 BookService 注入到该测试类中

@SpringBootTest
class Springboot07TestApplicationTests {

@Autowired
private BookService bookService;

@Test
public void save() {
bookService.save();
}
}

注意:必须同层包。

例如:

  • 引导类所在包是 com.itheima
  • 测试类所在包是 com.itheima

如果不满足,就指定进来,主要是那个main类。

9、SpringBoot整合mybaits

1)创建项目时加上相应的起步依赖。

2)在resources下加个 application.yml 配置文件:

spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db
username: root
password: root

3)测试出现错误信息,原因是 Mybatis 会扫描接口并创建接口的代码对象交给 Spring 管理,但是现在并没有告诉 Mybatis 哪个是 dao 接口。在BookDao 接口上使用 @MapperBookDao 接口改进为

//让SpringBoot扫描到这个组件,生成自动代理
@Mapper
public interface BookDao {
@Select("select * from tbl_book where id = #{id}")
public Book getById(Integer id);
}

4)使用Druid数据源

我们并没有指定数据源,SpringBoot 有默认的数据源,我们也可以指定使用 Druid 数据源。

  • 导入 Druid 依赖<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.16</version>
    </dependency>
  • application.yml 配置文件配置可以通过 spring.datasource.type 来配置使用什么数据源。配置文件内容可以改进为spring:
    datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource
文末附加内容
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇