Skip to content

SpringBoot

spring-boot-logo

SpringBoot概述

为了解决以下两点问题:

  1. 自动配置,需要程序员自己配置的内容会少很多

  2. 内置 Tomcat,更灵活更敏捷地部署项目

SpringBoot入门

SpringBoot快速入门

导入依赖

xml
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
    </parent>

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

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

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

编写启动器

java
@SpringBootApplication
public class SpringBootStarter {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootStarter.class, args);
    }
}

编写UserController

java
@Controller
@RequestMapping("/user")
public class UserController {

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

SpringBoot项目的3种启动方式

  1. 在 Idea 中,打开启动类 java 文件,点击左侧的"Debug"按钮

必须要提前装好jdk、maven、idea

  1. 打成 jar 包,在命令行/控制台,java -jar J2101-0607-springboot.jar

在窗口的最右侧,找到"Maven",在生命周期中,找到"package",打包 在项目中的target目录中,会找到这个jar包 在电脑的资源管理器中,打开cmd命令窗口 执行java -jar jar文件名 必须要提前装好jdk

  1. 利用 maven 插件启动

mvn spring-boot:run 在Idea窗口的最右侧,找到"Maven",找到"plugins",找到spring-boot,找到spring-boot:run 必须要提前装好jdk、maven、idea

SpringBoot核心配置文件

多环境配置

  • application-dev.properties

    properties
    server.port=8080
  • application-prod.properties

    properties
    server.port=9090
  • application.properties

    properties
    spring.profiles.active=prod

引用配置信息

编辑springboot核心配置文件
  • application.properties
properties
custom.username=root
custom.password=root
custom.url=jdbc:mysql://localhost:3306/abc
编写配置文件读取类
  • CustomConfig.java
java
@Component
@ConfigurationProperties(prefix = "custom")
// prefix: 前缀
public class CustomConfig {
    // custom.username
    private String username;

    // custom.password
    private String password;

    // custom.url
    private String url;

    // Generate getter and setter...
}
其他代码
  • Application.java
java
@SpringBootApplication

// ComponentScan直译: 注解扫描
@ComponentScan("com.futureweaver")
public class SpringBootStarter {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootStarter.class, args);
    }
}
  • CustomController.java
java
@Controller
public class CustomController {
    @Autowired
    private CustomConfig config;

    @RequestMapping("/read_username")
    @ResponseBody
    public String readUsername() {
        return config.getUsername();
    }

    @RequestMapping("/read_password")
    @ResponseBody
    public String readPassword() {
        return config.getPassword();
    }

    @RequestMapping("/read_url")
    @ResponseBody
    public String readUrl() {
        return config.getUrl();
    }
}

热加载

导入依赖

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

Idea配置

  1. All Settings
  2. Build, Execution, Deployment
  3. Compiler
  4. Build project automatically

重新部署项目

当项目修改了代码时,需要重新部署项目

  1. 菜单栏
  2. Build
  3. Build Project

SpringBoot深入

整合mybatis

mybatis配置【回顾】

核心配置文件
  1. settings
  2. typeAliases
  3. typeHandlers
  4. plugins
  5. environments
  6. mappers
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="lazyLoadingEnabled" value="true"/>
        <setting name="autoMappingBehavior" value="FULL"/>
        <setting name="logImpl" value="LOG4J"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <typeAliases>
        <package name="com.futureweaver.domain"/>
    </typeAliases>

    <typeHandlers>
        <package name="com.futureweaver.typehandlers"/>
    </typeHandlers>

    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"/>
    </plugins>

    <environments default="default">
        <environment id="default">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/db_shopping?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <package name="com.futureweaver.mapper"/>
    </mappers>
</configuration>
代码
  1. SqlSessionFactoryBuilder
  2. SqlSessionFactory
  3. SqlSession
  4. Mapper
java
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(is);
SqlSession sqlSession = factory.openSession();
XxxMapper mapper = sqlSession.getMapper(XxxMapper.class);

mybatis-spring配置【回顾】

xml
<util:properties id="druidConfiguration" location="classpath:druid.properties"/>

<!-- 配置数据源 -->
<bean id="dataSource"
      class="com.alibaba.druid.pool.DruidDataSourceFactory"
      factory-method="createDataSource"
      c:properties-ref="druidConfiguration"/>

<!-- 读取mybatis核心配置文件 -->
<bean id="mybatis-config"
      class="org.springframework.core.io.ClassPathResource"
      c:path="mybatis-config.xml"/>

<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory"
      class="org.mybatis.spring.SqlSessionFactoryBean"
      p:configLocation-ref="mybatis-config"
      p:dataSource-ref="dataSource"/>

<!-- 配置mapper扫描 -->
<bean id="mapperScannerConfigurer"
      class="org.mybatis.spring.mapper.MapperScannerConfigurer"
      p:basePackage="com.futureweaver.mapper"/>

<!-- 配置事务处理器 -->
<bean id="tx"
      class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
      p:dataSource-ref="dataSource"/>

mybatis-spring-boot配置

pom.xml
xml
<!-- mysql -->
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
</dependency>

<!-- druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.20</version>
</dependency>

<!-- mybatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>3.0.2</version>
</dependency>
application.properties
properties
# mybatis配置

logging.level.com.futureweaver=DEBUG

# 以下两种方式任选其一
# 第1种: 引入mybatis-config.xml文件
# BEGIN
mybatis.config-location=classpath:mybatis-config.xml
# END

# 第2种: mybatis-settings标签
# BEGIN
mybatis.configuration.cache-enabled=false
mybatis.configuration.local-cache-scope=statement
mybatis.configuration.lazy-loading-enabled=true
mybatis.configuration.auto-mapping-behavior=full
mybatis.configuration.log-impl=org.apache.ibatis.logging.slf4j.Slf4jImpl
mybatis.configuration.map-underscore-to-camel-case=true

# mybatis-typeAliases标签
mybatis.type-aliases-package=com.futureweaver.domain

# mybatis-typeHandler标签
# mybatis.type-handlers-package=com.futureweaver.typehandler

# mybatis-plugins标签
# 不配置,导入mybatis插件的xxx-spring-boot-start会自动配置

# mybatis-environments标签
# 不配置,spring把数据源注入mybatis当中

# mybatis-mappers标签
# 注意此标签,不会扫描包,只会从SqlSessionFactoryBuilder -> SqlSessionFactory -> SqlSession,才会生效
# mybatis.mapper-locations
# END

# 连接数据库的信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db_shopping?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
Application.java
java
@SpringBootApplication
@ComponentScan("com.futureweaver")

// 在哪个包里扫描mapper
@MapperScan("com.futureweaver.mapper")
public class SpringBootStarter {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootStarter.class, args);
    }
}

整合pagehelper

导入依赖

xml
<!-- pagehelper依赖 -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.3.0</version>
</dependency>

测试

  • ContactController.java
java
@Controller
@RequestMapping("/contact")
public class ContactController {
    @Autowired
    private ContactService service;

    @RequestMapping("/query_all")
    @ResponseBody
    public PageInfo<ContactInfo> queryAll(@RequestParam(defaultValue = "1") int currentPage,
                                          @RequestParam(defaultValue = "10") int pageSize) {
        return service.queryAll(currentPage, pageSize);
    }
}
  • ContactService.java
java
@Service
public class ContactService {
    @Autowired
    private ContactMapper mapper;

    public PageInfo<ContactInfo> queryAll(int currentPage, int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<ContactInfo> contacts = mapper.queryAll();
        PageInfo<ContactInfo> pageBean = new PageInfo<>(contacts);
        return pageBean;
    }
}

整合JSP

导入依赖

xml
<!-- JSP -->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>

<!-- jakarta.servlet.jsp.jstl-api -->
<dependency>
    <groupId>jakarta.servlet.jsp.jstl</groupId>
    <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
    <version>3.0.0</version>
</dependency>

<!-- jakarta.servlet.jsp.jstl -->
<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>jakarta.servlet.jsp.jstl</artifactId>
    <version>3.0.1</version>
</dependency>

配置视图解析器

properties
spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp

整合Thymeleaf

导入依赖

  • org.springframework.boot:spring-boot-starter-thymeleaf

编写html资源

html文件的存放位置

  • 模板页面写到src/main/resources/templates目录下
  • 静态页面写到src/main/resources/static目录下
  • accounts.html
html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<table>
    <tr th:each="account : ${account}">
        <td th:text="${account.id}"></td>
        <td th:text="${account.name}"></td>
        <td th:text="${account.balance}"></td>
    </tr>
</table>
</body>
</html>

整合JUnit

导入依赖

  • org.springframework.boot:spring-boot-starter-test
  • junit:junit

编写测试类

java
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootStarter.class)

Idea模板

  1. 进入Idea欢迎页面(如果已开启某个项目,点击菜单栏-File-Close Project)
  2. 左侧导航栏,选择Customize,选择All Settings...
  3. 左侧导航栏,选择Editor->File And Code Templates

pom.xml

  1. 右侧视图,选择Other选项卡
  2. 右侧窗口中的左侧导航栏,选择Maven->Maven Project.xml
  3. 将以下文本,全部 CV 替换
xml
<?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>

#if (${HAS_PARENT})
    <parent>
        <groupId>${PARENT_GROUP_ID}</groupId>
        <artifactId>${PARENT_ARTIFACT_ID}</artifactId>
        <version>${PARENT_VERSION}</version>
#if (${HAS_RELATIVE_PATH})
        <relativePath>${PARENT_RELATIVE_PATH}</relativePath>
#end
    </parent>

#end

    <groupId>${GROUP_ID}</groupId>
    <artifactId>${ARTIFACT_ID}</artifactId>
    <version>${VERSION}</version>

#if (${SHOULD_SET_LANG_LEVEL})
    <properties>
        <maven.compiler.source>${COMPILER_LEVEL_SOURCE}</maven.compiler.source>
        <maven.compiler.target>${COMPILER_LEVEL_TARGET}</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
#end

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.7</version>
    </parent>

    <dependencies>
        <!-- spring-boot-starter-web -->
        <!-- spring-boot-starter -->
        <!-- spring-boot-starter-test -->
        <!-- spring-boot-starter-jdbc -->
        <!-- spring-boot-devtools -->
        <!-- hibernate-validator -->
        <!-- mysql-connector-j -->
        <!-- druid-spring-boot-starter -->
        <!-- mybatis-spring-boot-starter -->
        <!-- pagehelper-spring-boot-starter -->

        <!-- log4j -->
        <!-- junit -->
    </dependencies>

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

        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>*.xml</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>

            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>*</include>
                    <include>**/*</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
</project>

application.properties

properties
# logging
logging.level.root=debug
logging.level.com.futureweaver=debug
logging.pattern.console=%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID}){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx
#logging.file.name=...
#logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID} --- [%t] %-40.40logger{39} : %m%n%wEx

# mybatis-settings
mybatis.configuration.lazy-loading-enabled=true
mybatis.configuration.auto-mapping-behavior=full
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.cache-enabled=false
mybatis.configuration.local-cache-scope=statement

# mybatis-typeAliases
mybatis.type-aliases-package=${mybatis_type_aliases_package}

# datasource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/${db_name}?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
spring.datasource.username=${db_username}
spring.datasource.password=${db_password}
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

log4j.properties

properties
global.conversion.pattern=[%-5p] [%d] [%l] %n%m%n%n

# root
log4j.rootLogger=DEBUG,stdout

# ConsoleAppender
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Threshold=DEBUG
log4j.appender.stdout.Encoding=utf-8
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=${global.conversion.pattern}

mybatis-mapper.xml

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="${PACKAGE_NAME}.${NAME}">

</mapper>

CorsConfig.java

java
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig{
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setAllowCredentials(true);
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        return new FilterRegistrationBean<>(new CorsFilter(source));
    }
}

课程目标总结

  • 能够理解 SprintBoot 的特点
  • 能够理解 SpringBoot 的核心功能
  • 能够搭建 SpringBoot 的环境
  • 能够完成 application.properties 文件的配置
  • 能够完成 application.yml 文件的配置
  • 能够使用 SpringBoot 集成 Mybatis
  • 能够使用 SpringBoot 集成 Junit