SpringBoot

2022-12-04  本文已影响0人  h2coder

SpringBoot简介

SpringBoot快速入门

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itheima</groupId>
    <artifactId>day37-01-spring-boot-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--
        配置父模块
        推荐版本:
            2.6.2
            2.5.0
            2.3.9.RELEASE
     -->
    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.5.0</version>
    </parent>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- 导入SpringBoot的Web启动器:SpringMVC环境依赖的所有Jar包 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>
//springboot启动引导类注解,里面有@ComponentScan
//@ComponentScan 开启IOC注解扫描,没有配置包名,默认当前包及其子包所有类
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        //启动springboot程序运行当前引导类
        SpringApplication.run(DemoApplication.class, args);
    }
}
@RestController
@RequestMapping("/book")
public class BookController {
    @GetMapping
    public String hello() {
        return "hello spring boot";
    }
}

运行DemoApplicationmain方法,浏览器访问http://localhost:8080/book,浏览器显示hello spring boot就为SpringBoot工程搭建成功

打包SpringBoot工程为jar包

如果需要将SpringBoot工程打包为jar,并使用命令行运行,则需要配置一个maven插件

<!-- 配置插件,独立运行 -->
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

运行以下命令,如打包成功,将会在工程模块的target目录下生成jar包,在改目录下进行终端命令行,使用java -jar xx.jar即可启动

mvn package

SpringBoot项目配置

SpringBoot提供了多种属性配置方式,properties、yml、yaml,一共3种方式

以修改服务器端口为例,修改端口从8080修改为80

server.port=80
server:
  port: 81
server:
  port: 82

SpringBoot配置文件加载顺序

综上所述,3种配置文件如果都同时存在,那么配置文件加载顺序是怎样呢?

yaml介绍

什么是yaml,和properties有什么区别?

yaml语法规则

yaml数组数据

lesson: SpringBoot

server:
  port: 8080

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

yaml数据读取

一共有3种获取yaml数据的方式

注:这种方式只能注入单个数值

@RestController
@RequestMapping("/book")
public class BookController {
    @Value("${lesson}")
    private String lesson;

    @Value("${server.port}")
    private Integer port;

    /**
     * 注解 @Value,这个注解不能读取整个数组,只能获取数组中的其中一个元素
     * 使用注意:读取配置文件的数据,配置文件配置这个数据,并且要正确,否则就会报错
     */
    @Value("${enterprise.subject[0]}")
    private String subject;

    @GetMapping("hello")
    public String hello() {
        System.out.println("lesson = " + lesson);
        System.out.println("server.port = " + port);
        System.out.println("enterprise.subject = " + subject);
        return "hello spring boot";
    }
}

注:数组元素也只能一个个取出来

@RestController
@RequestMapping("/book")
public class BookController {
    /**
     * 环境对象,最灵活,但是可读性差
     */
    @Autowired
    private Environment environment;

    @GetMapping("/hello2")
    public String hello2() {
        System.out.println("lesson = " + environment.getProperty("lesson"));
        System.out.println("server.port = " + environment.getProperty("server.port"));
        System.out.println("enterprise.subject[0] = " + environment.getProperty("enterprise.subject[0]"));
        System.out.println("enterprise.subject[1] = " + environment.getProperty("enterprise.subject[1]"));
        System.out.println("enterprise.subject[2] = " + environment.getProperty("enterprise.subject[2]"));
        return "hello spring boot";
    }
}
  1. 将对象添加Spring容器中,在类上添加@Component注解
  2. 在类上添加@ConfigurationProperties(prefix="指定前缀")
  3. 添加get和set方法,toString方法
  4. 在控制器中注入下面Enterprise对象

注:使用lombok需要在pom.xml中导入坐标

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
//封装yml数据到一个实体类中
//lombok生成getter、setter、toString方法
@Data
//将该类创建对象,并加入IOC容器
@Component
//指定封装的数据的前缀
@ConfigurationProperties(prefix = "enterprise")
public class Enterprise {
    private String name;
    private Integer age;
    private List<String> subject;
}
@RestController
@RequestMapping("/book")
public class BookController {
    /**
     * 读取到的配置会封装到这个对象
     */
    @Autowired
    private Enterprise enterprise;

    @GetMapping("/hello3")
    public String hello3() {
        System.out.println("name = " + enterprise.getName());
        System.out.println("age = " + enterprise.getAge());
        System.out.println("enterprise.subject[0] = " + enterprise.getSubject().get(0));
        return "hello spring boot";
    }
}
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

多环境开发配置

项目的开发环境、测试环境、生产环境的配置信息一般都不一致,SpringBoot提供了多环境配置满足该需求

多环境配置分类yaml文件多环境配置以及properties文件多环境配置

yaml文件多环境配置,是将多个环境的配置写到同一个yaml文件中

application.yml中,添加如下配置,每种配置以---分割,通过active激活(使用)指定的环境

spring:
  profiles:
    active: pro
    
---
spring:
  config:
    activate:
      on-profile: pro
server:
  port: 80

---
spring:
  config:
    activate:
      on-profile: test
server:
  port: 81

---
spring:
  config:
    activate:
      on-profile: dev
server:
  port: 82

properties多环境配置,是将多个环境的配置单独配置在一个properties文件中,配置文件都以application-开头,-后加上环境的名称,以properties作为文件拓展名

#主启动配置文件 application.properties
spring.profiles.active=pro
#环境分类配置文件 application-pro.properties
server.port=80
#环境分类配置文件 application-dev.properties
server.port=81
#环境分类配置文件application-test.properties
server.port=82

多环境启动

通过mvn package命令打包后,就可以通过java -jar springboot.jar的方式启动,在该命令后面添加环境参数,即可切换对应的环境以及端口号

# 指定哪个配置名
java –jar springboot.jar --spring.profiles.active=test
# 指定具体的参数
java –jar springboot.jar --server.port=88
# 同时指定配置名 端口号
java –jar springboot.jar --server.port=88 --spring.profiles.active=test

SpringBoot多环境与Maven多环境兼容

本身maven就提供了多环境切换的功能,它提供了idea的GUI页面进行切换,而SpringBoot的多环境配置切换只能使用命令行

但SpringBoot也提供了与Maven多环境的兼容,使得在IDEA的maven多环境切换页面中,切换SpringBoot的多环境配置

<!-- 多环境配置,在这里配置SpringBoot的环境名字,用户通过勾选界面,获取指定的SpringBoot名字 -->
<profiles>
    <profile>
        <!-- maven环境的名字 -->
        <id>dev_env</id>
        <!-- SpringBoot的环境名字 -->
        <properties>
            <profile.active>dev</profile.active>
        </properties>
        <!-- 默认激活 -->
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>

    <profile>
        <id>pro_env</id>
        <properties>
            <profile.active>pro</profile.active>
        </properties>
    </profile>

    <profile>
        <id>test_env</id>
        <properties>
            <profile.active>test</profile.active>
        </properties>
    </profile>
</profiles>

注:Maven的多环境配置,需要配合propertis配置文件,所以需要将该配置文件中的多环境配置先注释,再加上配置占位符

# 配合maven进行多环境配置
spring.profiles.active=${profile.active}

注:如果不配置,propertis配置文件中的${profile.active}将不会生效!!!

<build>
    <plugins>
        <!-- 配置maven去 resource 目录下,解析里面的 ${profile.active} 替换为上面用户在勾选页面对应的配置值 -->
        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <configuration>
                <encoding>utf-8</encoding>
                <useDefaultDelimiters>true</useDefaultDelimiters>
            </configuration>
        </plugin>
    </plugins>
</build>

SpringBoot集成第三方技术

SpringBoot集成JUnit

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
@SpringBootApplication
public class JunitApplication {
    public static void main(String[] args) {
        SpringApplication.run(JunitApplication.class, args);
    }
}
/**
 * 业务层接口
 */
public interface BookService {
    void save();
}

/**
 * 业务层实现类
 */
//创建对象,并加入IOC容器
@Service
public class BookServiceImpl implements BookService {
    @Override
    public void save() {
        System.out.println("book service success...");
    }
}
/**
 * 注解 @SpringBootTest,会去找引导类 JunitApplication ,并且运行引导类(里面有创建IOC容器对象,并扫描IOC注解)
 * <p>
 * 第一种用法:@SpringBootTest 测试的类必须放在与引导类同包名及其子包下,就不用手动指定引导类,会自动查找运行
 * 第二种用法:@SpringBootTest(classes = JunitApplication.class)
 * - 当测试类不在引导类所在包及其子包下时,都需要手动指定引导类
 * 注意:只用这个注解的前提是,必须Junit5
 * 如果是Junit4,必须再加一个 @RunWith(SpringJUnit4ClassRunner.class) 注解,并把 @Test 注解的导包换成 org.junit.Test 才可以
 * Junit5,导包是 org.junit.jupiter.api.Test
 * 即是:
 * - @RunWith(SpringJUnit4ClassRunner.class)
 * - @SpringBootTest
 */
@SpringBootTest
public class BookServiceTest {
    @Autowired
    private BookService bookService;

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

SpringBoot集成SSM

SpringBoot的web启动器,已经将Spring与SpringMVC进行了整合,我们只需要将MyBatis在进行整合即可!

  1. SpringBoot整合Spring(不存在)
  2. SpringBoot整合SpringMVC(不存在)
  3. SpringBoot整合MyBatis(主要)
<dependencies>
    <!-- mybatis启动器 -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>

    <!-- web启动器 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- 连接池 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.2.6</version>
    </dependency>

    <!-- 测试 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>

    <!-- lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>

    <!-- mysql驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

注意:SpringBoot版本低于2.4.3(不含),Mysql驱动版本大于8.0时,需要在url连接串中配置时区,或在MySQL数据库端配置时区解决此问题

# 配置连接池
spring:
  datasource:
    # 配置MySQL驱动
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 配置使用Druid连接池
    type: com.alibaba.druid.pool.DruidDataSource
    # 配置连接地址以及用户名和密码
    url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false
    username: root
    password: root

# mybatis配置
mybatis:
  # 配置实体类别名的包扫描
  type-aliases-package: com.itheima.pojo
  configuration:
    # 开启小驼峰命名映射
    map-underscore-to-camel-case: true
    # 开启控制台sql语句日志打印
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
@SpringBootApplication
//SpringBoot 扫描MyBatis接口,生成代理对象,加入IOC容器(推荐使用)
@MapperScan("com.itheima.mapper")
public class SSMApplication {
    public static void main(String[] args) {
        SpringApplication.run(SSMApplication.class, args);
    }
}
@Data //lombok的注解,可以给实体类生成set\get和重写toString()方法
@AllArgsConstructor //2.生成全参构造函数
@NoArgsConstructor //3.生成无参构造函数
public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;
}

Mapper接口类,需要添加@Mapper接口或在启动类上添加@MapperScan注解,包扫描包下的Mapper接口

//注解 @Mapper,标识这是MyBatis接口,会自动创建对象,加入IOC容器
//不推荐,因为每个Mapper接口都需要设置,代码冗余,推荐在启动类中使用 @MapperScan("com.itheima.mapper") 进行包扫描
//@Mapper
public interface BookMapper {
    /**
     * 查询所有图书
     */
    @Select("select * from tbl_book")
    List<Book> findAll();
}
/**
 * 业务层接口
 */
//开启事务,在SpringBoot中,不需要开启事务注解扫描,因为默认已经开启,所以该注解可以直接使用
@Transactional
public interface BookService {
    /**
     * 查询所有图书
     */
    List<Book> findAll();
}

/**
 * 业务层实现类
 */
//创建对象,并加入IOC容器
@Service
public class BookServiceImpl implements BookService {
    @Autowired(required = false)
    private BookMapper bookMapper;

    @Override
    public List<Book> findAll() {
        return bookMapper.findAll();
    }
}

运行SSMApplicationmain方法,浏览器访问http://localhost:8080/book/findAll,浏览器显示json数据即为成功

@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping("/findAll")
    public List<Book> findAll() {
        return bookService.findAll();
    }
}

也可以使用SpringBoot集成Junit,进行Mapper(数据持久层)的单元测试

@SpringBootTest
class BookMapperTest {
    @Autowired
    private BookMapper bookMapper;

    @Test
    public void testFindAll() {
        List<Book> bookList = bookMapper.findAll();
        for (Book book : bookList) {
            System.out.println(book);
        }
    }
}

SpringBoot静态资源处理

SpringBoot的默认的静态资源访问路径有四个,我们只需要将前端静态资源方法四个路径中的任意一个,都可以实现前端资源的访问(注:访问时,不需要添加具体存放的目录,直接访问资源即可)

例如,在static目录中提供index.html页面,并通过浏览器访问该页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index3</title>
</head>
<body>
static目录下的index.html
</body>
</html>
http://localhost:8080/index.html
上一篇下一篇

猜你喜欢

热点阅读