Springboot基础入门

认识Springboot

SpringBoot是由Pivotal团队在2014年4月发布第一个版本的全新开源的轻量级框架。它基于Spring4.0设计,不仅继承了Spring框架原有的优秀特性,而且还通过简化配置来进一步简化了Spring应用的整个搭建和开发过程。另外SpringBoot通过集成大量的框架使得依赖包的版本冲突,以及引用的不稳定性等问题得到了很好的解决。
SpringBoot对Spring和第三方类库进行了封装,大部分的配置都被SpringBoot自动装配了,可以用最少的配置开发项目。大多数的SpringBoot项目只需要很少的配置。

一、创建简单示例工程

创建一个springMVC的工程。SpringBoot 用一个普通的java工程就可以运行web应用。它没有springMVC的xml配置文件,也没有web.xml

1)、引入依赖包pom.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>

    <groupId>com.test.springboot</groupId>
    <artifactId>springboot01</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--引入springboot父版本-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--整合springMVC及相关配置文件-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    <build>
        <!--将springboot的应用程序打包成fat jar的插件-->
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2)、创建controller

package com.test.boot.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("index")
    public String hello(){
        return "hello Springboot";
    }
}

3)、创建启动类

package com.test.boot.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication//表示当前类是springboot的启动类
public class TestBootStarter {
    public static void main(String[] args) {
        //启动当前启动类
        SpringApplication.run(TestBootStarter.class,args);
    }
}

@SpringBootApplication: SpringBoot项目的核心注解,主要目的是开启自动配置。可以将程序以web方式运行
启动main方法,浏览器访问:
在这里插入图片描述
或者配置了spring- boot-maven-plugin后,使用maven命令启动: spring-boot:run

注意:
1、spring启动类在不设置ComponentScan的情况下默认会去找当前类所在的包以及子包所有bean,spring启动类放的位置要合适,如果放的包范围广,扫描的范围大,导致项目运行慢,放的子包范围小,可能扫描不到其他需要被扫描的包。
2、springboot中需要什么包引入什么包,如果引入不需要的包没有进行相关配置,可能会报错。

二、SpringBoot核心相关内容

1、入口类

SpringBoot通常有一一个入口类* Application,内部有一个main方法,是启动SpringBoot的入口。
使用@SpringBootApplication注解,幷包含main方法。

2、常见注解

@SpringBootApplication:是SpringBoot的核心注解,用于标注程序时一个SpringBoot程序。它是一个组合注解,由多个注解组合而成。
@SpringBootApplication = @ComponentScan+@Configuration+@EnableAutoConfiguration

@ComponentScan:组件扫描,可发现和自动装配一些bean。 默认扫描@SpringBootApplication类所在包的同级目录以及它的子目录。

@SpringBootConfiguration: 一个组合注解,相当于传统的xml配置文件,包含@Configuration注解。在SpringBoot 项目中推荐使用@SpringBootConfiguration替代@Configuration。

@EnableAutoConfiguration:启用自动配置,该注解会使Spring Boot 根据项目中依赖的jar包自动配置项目的配置项,这也是springboot 的核心注解之一,我们只需要将项目需要的依赖包加入进来,它会自动帮我们配置这个依赖需要的基本配置。比如我们的项目引入了spring-boot-starter-web依赖,springboot会自动帮我们配置tomcat 和springmvc

设置不自动装配:

@SpringBootApplication(exclude = {JpaRepositoriesAutoConfiguration.class,RedisAutoConfiguration.class})

注解内部将不需要自动配置的依赖通过exclude参数指定即可,可以指定多个类

@Bean:注解在方法上, 声明当前方法返回一个Bean

@PostConstruct:注解在方法上,构造函数执行后执行。

@PreDestroy:注解在方法上,在Bean销毁前执行。

@Lazy(true):延迟初始化

@Scope:注解在类上,描述spring容器如何创建Bean实例。

@Profile:注解在方法类上在不同情况下选择实例化不同的Bean特定环境下生效

@Import:用来导入其他配置类。

@ImportResource:用来加载xml配置文件。

3、核心配置文件
1)、ymI和properties

SpringBoot使用一个全局配置文件application.properties或者application.yml。
yml类似于xml,但是yml没有xml中的标签,而是通过空格来表示层级结构:

#相当于properties中的server.port=80
server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/exam?characterEncoding=utf8
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver

SpringBoot的配置文件可以放在以下几个地方:
外置,在相对于应用程序运行目录的/config子目录里。(resources/config)
外置,在应用程序运行的目录里(resources)
内置,在config包
内置,在Classpath根目录
这个列表按照优先级排序,也就是说,src/main/resources/config下application.properties覆盖src/main/resources下application.properties中相同的属性。
在这里插入图片描述
如果在相同优先级位置同时有application.properties 和application.yml, 那么application.properties里的属性里面的属性就会覆盖application.yml
如果自己定义了其它的配置文件,如test.properties, 可以使用@PropertiesSource注解指定加载配置文件。

@PropertySource("classpath:test.properties")

在这里插入图片描述

2)、profile多环境配置

当应用程序需要部署到不同运行环境时,一些配置细节通常会有所不同,最简单的比如日志,生产日志会将日志级别设置为WARN或更高级别,并将日志写入日志文件,而开发的时候需要日志级别为DEBUG,日志输出到控制台即可。
如果按照以前的做法,就是每次发布的时候替换掉配置文件,这样太麻烦了,SpringBoot的Profile 就给我们提供了解决方案,命令带上参数就搞定。

切换的配置文件必须符合application-xx的命名,其中xx和application.properties中指定的属性值对应,在application.properties中进行如下配置,系统将会使用application-dev.properties中的配置:

spring.profiles.active=online

在这里插入图片描述

三、springboot业务示例工程

1、创建工程

创建maven工程

2、引入依赖包
<?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.test.springboot</groupId>
    <artifactId>springboot01</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <!--引入springboot父版本-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--整合springMVC及相关配置文件-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.29</version>
        </dependency>
        <!--jsp需要引入的包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

    <!--配置资源文件扫描,否则Mapper-->
    <build>
        <!--将springboot的应用程序打包成fat jar的插件-->
        <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>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                    <include>**/*.yml</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>
3、创建实体类
package com.test.boot.pojo;

public class Dept {
    private Integer id;
    private String name;
	//以下略
}
4、dao层

dao接口

package com.test.boot.dao;

import com.test.boot.pojo.Dept;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;

import java.util.List;

public interface DeptDAO {
    List<Dept> getDeptList();

    @Insert("insert into DEPT(name) value(#{name})")
    @Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")
    void addDept(Dept dept);
}

mapper映射

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.boot.dao.DeptDAO">
    <select id="getDeptList"  resultType="Dept">
        select id,name from dept
    </select>
</mapper>
5、service层

service接口

package com.test.boot.service;

import com.test.boot.pojo.Dept;

import java.util.List;

public interface DeptService {
    List<Dept> getDeptList();

    void addDept(Dept dept);
}

service实现类

package com.test.boot.service.impl;

import com.test.boot.dao.DeptDAO;
import com.test.boot.pojo.Dept;
import com.test.boot.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptDAO deptDAO;
    @Override
    public List<Dept> getDeptList() {
        return deptDAO.getDeptList();
    }
    @Override
    public void addDept(Dept dept) {
        deptDAO.addDept(dept);
    }
}
6、controller代码
package com.test.boot.controller;

import com.test.boot.pojo.Dept;
import com.test.boot.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class DeptController {
    @Autowired
    private DeptService deptService;
    @RequestMapping("list.html")
    public String list(Model model){
        List<Dept> list = deptService.getDeptList();
        model.addAttribute("list",list);
        return "list";
    }

    @RequestMapping("add.html")
    public String add(Dept dept){
        deptService.addDept(dept);
        return "redirect:list.html";
    }

}
7、jsp页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="add.html" method="post">
        部门名:<input type="text" name="name" /><br>
        <input type="submit" value="add"/>
    </form>
    <c:forEach items="${list}" var="d">
        ${d.id}-${d.name}<br />
    </c:forEach>
</body>
</html>
8、启动类
package com.test.boot;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import javax.sql.DataSource;
import java.util.Properties;

@SpringBootApplication//表示当前类是springboot的启动类
@EnableTransactionManagement//开启事务管理
@PropertySource("classpath:test.properties")
@MapperScan(basePackages = "com.test.boot.dao")
public class TestBootStarter {
    public static void main(String[] args) {
        //启动当前启动类
        SpringApplication.run(TestBootStarter.class,args);
    }
    //aop切入点
    public static final String transactionExecution = "execution (* com.test.boot.service..*(..))";

    @Autowired
    private DataSource dataSource;

    //声明式事务
    @Bean
    public DefaultPointcutAdvisor defaultPointcutAdvisor(){
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(transactionExecution);
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
        advisor.setPointcut(pointcut);
        Properties attributes = new Properties();
        attributes.setProperty("add*", "PROPAGATION_REQUIRED,-Exception");//有异常进行回滚
        attributes.setProperty("update*", "PROPAGATION_REQUIRED,-Exception");
        attributes.setProperty("delete*", "PROPAGATION_REQUIRED,-Exception");
        TransactionInterceptor txAdvice = new TransactionInterceptor(new DataSourceTransactionManager(dataSource), attributes);
        advisor.setAdvice(txAdvice);
        return advisor;
    }
}
9、配置信息
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
  mvc:
    view:
      suffix: .jsp
server:
  port: 8080

mybatis:
  type-aliases-package: com.test.boot.pojo
  mapper-locations: classpath:com/test/boot/dao/mapper/*.xml

上面的程序只要启动main方法就可以访问了。

在这里插入图片描述
如果需要打包发布到tomcat,需要再配置一个ServletInitializer,否则tomcat启动后会404

package com.test.boot;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(TestBootStarter.class);
    }
}

四、Springboot整合ssm

1、整合准备

以前面已有的ssm工程来进行整合:SSM框架实现后台管理系统权限管理
github项目文件地址:https://github.com/booy123/ssmdemo
项目结构图
在这里插入图片描述

2、清理配置文件

删除spring-config.xml、springMVC-servlet.xml、jdbc.properties
清理了web.xml的配置信息
在这里插入图片描述

3、pom.xml中的依赖包替换

ssm中的原pom.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>

    <groupId>org.example</groupId>
    <artifactId>ssmdemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <properties>
        <spring.version>5.1.3.RELEASE</spring.version>
    </properties>

    <dependencies>
        <!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!-- mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.29</version>
        </dependency>
        <!--日志包-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.1</version>
        </dependency>
        <!--spring数据库-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--aop-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring核心包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring-mybatis整合包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--spring相关包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--实体类注解-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.22</version>
        </dependency>
        <!--分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.2.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!--json依赖-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <!--配置资源文件扫描,否则Mapper-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>

</project>

1)、mybatis部分
上面的Spring项目中需要引入:

		<!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!--spring-mybatis整合包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

整合后:

		<!--整合mybatis包及相关配置文件-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

2)、spring部分

整合前:
上面的Spring项目中需要引入spring相关包:

		<!--spring数据库-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--aop-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring核心包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring相关包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--json依赖-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.0</version>
        </dependency>

整合后:
先引入父版本

	<!--引入springboot父版本-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/>
    </parent>

spring-boot-starter-web中内置了tomcat,整合后需要引入:

		<!--整合springMVC及相关配置文件-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

springboot默认不支持jsp,如果需要使用jsp需要单独引入jsp包:

<!--spring默认不支持jsp,要使用jsp页面需要单独引入jsp包-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

 
3)、pagehelper替换成springboot的包

		<!--翻页配置-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>

整合后的pom.xml,注释中的改动替换部分为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>org.example</groupId>
    <artifactId>ssmdemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
<!--改动替换部分-->    
    <!--引入springboot父版本-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/>
    </parent>
    <dependencies>
        <!--整合mybatis包及相关配置文件-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--整合springMVC及相关配置文件-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--spring默认不支持jsp,要使用jsp页面需要单独引入jsp包-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!--boot翻页配置-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>

<!--不变的部分-->
        <!-- mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.29</version>
        </dependency>
        <!--日志包-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.1</version>
        </dependency>

        <!--实体类注解-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.22</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
    <!--配置资源文件扫描,否则Mapper-->
    <build>
        <!--将springboot的应用程序打包成fat jar的插件-->
        <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>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>
4、变动配置文件

创建application.properties配置不同项目需要变动的部分

#数据源的基本信息
spring.datasource.url=jdbc:mysql://localhost:3306/exam?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driverClassName = com.mysql.jdbc.Driver

#mybatis中mapper文件的路径
mybatis.mapper-locations=classpath*:com/booy/ssm/exam/dao/mapper/*.xml
#起别名。可省略些mybatis的xml中的resultType的全路径
mybatis.type-aliases-package=com.booy.ssm.exam.pojo

#springMVC中的视图信息,响应前缀
spring.mvc.view.prefix=/WEB-INF/pages/
#响应页面默认后缀
spring.mvc.view.suffix=.jsp
#DispatcherServlet中响应的url-pattern
server.sevlet-path=*.html
5、启动类

SpringBoot通常有一个入口类*Application,内部有一一个main方法,是启动SpringBoot的入口。

package com.booy.ssm.exam;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = "com.booy.ssm.exam.dao")
public class ExamStarter {
    public static void main(String[] args) {
        SpringApplication.run(ExamStarter.class,args);
    }
}

整合后项目结构图
在这里插入图片描述

五、启动原理解析

任何一个SpringBoot程序都有一个启动类:
启动类中包含@SpringBootApplication注解和SpringApplication.run()方法

@SpringBootApplication//表示当前类是springboot的启动类
public class TestBootStarter {
    public static void main(String[] args) {
        //启动当前启动类
        SpringApplication.run(TestBootStarter.class,args);
    }
 }
1、@SpringBootApplication

@SpringBootApplication是一个组合注解,除了基本的原信息标注以外,重要的注解有三个:

@Configuration
@EnableAutoConfiguration
@ComponentScan

如下代码等同于使用@SpringBootApplication注解
每次写三个注解比较繁琐,所以使用@SpringBootAplication更方便。

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class TestBootStarter {
    public static void main(String[] args) {
        SpringApplication.run(TestBootStarter.class,args);
    }
@Configuration

简单的说,SpringBoot 中使用一个@Configuration注解的类代替xml配置文件。
如spring-config.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--定义bean-->
</beans>

SpringBoot中写成:

import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringConfig {
}

如果定义一个bean,xml中写成:

<bean id= "dept" class="com.spring.test.springboot.pojo.Dept" >
    <property name = "id" value="1"/>
</bean>

SpringBoot中写成:

@Bean
public Dept dept(){
    Dept dept = new Dept() ;
    dept.setId(1);
    return dept;
}

SpringBoot中使用@Bean标注一个方法,该方法的方法名将默认成bean的id。生成的bean是单例的, 注意@Configuration的类要被@ComponentScan扫描到。

@ComponentScan

@ComponentScan自动扫描并加载符合规则的组件。可以通过basePackages 指定要扫描的包。如果不指定扫描范围,SpringBoot 默认会从生命@ComponentScan所在类的包进行扫描。

@ComponentScan(basePackages="com.spring.test.springboot.controller",
includeFilters={@ComponentScan.Filter(type=FilterType.ANNOTATION,value=Controller.class)})

等同于

<context:component-scan base-package=com.spring.test.springboot.controller>
<context:include-filter type="annotation"
        expression="org.springframework.stereotype.Controller" />
</context:component-scan>
@EnableAutoConfiguration

这个注解的作用是将所有符合自动配置条件的bean自动加载到loC容器。比如我们的项目引入了spring-boot-starter-web依赖,springboot会自动帮我们配置tomcat 和springmvc。@EnableAutoConfigutation中@Import了EnableAutoConfigurationlmportSelector,EnableAutoConfigurationlmportSelector类使用了Spring Core包的SpringFactoriesLoader 类的loadFactoryNamesof()方法。SpringFactoriesLoader 会查询META-INF/spring.factories文件中包
含的JAR文件。当找到spring.factories文件后,SpringFactoriesLoader 将查询配置文件命名
的属性。spring.factories 文件,内容如下:
在这里插入图片描述

2、SpringApplication

SpringApplication的run方法的实现是我们本次旅程的主要线路,该方法的主要流程大体可以归纳如下:
1)如果我们使用的是SpringApplication的静态run方法,那么,这个方法里面首先要创建一个SpringApplication对象实例,然后调用这个创建好的SpringApplication的实例方法。在SpringAppl ication实例初始化的时候,它会提前做几件事情:
a)根据classpath里面是否存在某个特征类
(org.springframework.web.context.ConfigurableWebApplicationContext)来决定是否应该创建一个为Web应用使用的ApplicationContext类型。
b)使用SpringFactoriesLoader在应用的classpath中查找并加载所有可用的ApplicationContextInitializer.
c)使用SpringFactoriesLoader在应用的classpath中查找并加载所有可用的ApplicationListener.
d)推断并设置main方法的定义类。

2)SpringApplication实例初始化完成并且完成设置后,就开始执行run方法的逻辑了,方法执行开始,首先遍历执行所有通过SpringFactoriesLoader可以查找到并加载的SpringApplicat ionRunListener。调用它们的started()方法,告诉这些SpringApplicationRunListener,“ 嘿,SpringBoot 应用要开始执行咯!”。

3)创建并配置当前Spring Boot应用将要使用的Environment ( 包括配置要使用的PropertySource以及Profile)。

4)遍历调用所有 SpringApplicationRunListener的environmentPrepared ()的方法,告诉他们:“当前SpringBoot应用使用的Environment准备好了咯!”。

5)如果SpringApplication的showBanner属性被设置为true,则打印banner。

6)根据用户是否明确设置了applicationContextClass类型以及初始化阶段的推断结果,决定该为当前SpringBoot应用创建什么类型的ApplicationContext并创建完成,然后根据条件决定是否添加ShutdownHook,决定是否使用自定义的BeanNameGenerator,决定是否使用自定义的ResourceLoader,当然,最重要的,将之前准备好的Env ironment设置给创建好的ApplicationContext使用。

7)ApplicationContext创建好之后,SpringApplication会再次借助Spring-FactoriesLoader,查找并加载classpath中所有可用的ApplicationContext- Initializer,然后遍历调用这些
ApplicationContextInitializer的initialize (applicationContext)方法来对已经创建好的ApplicationContext进行进一步的处理。

8)遍历调用所有SpringApplicationRunLi stener的contextPrepared()方法。

9)最核心的一步,将之前通过@EnableAutoConfiguration获取的所有配置以及其他形式的IoC容器配置加载到已经准备完毕的ApplicationContext。.

10)遍历 调用所有SpringApplicationRunListener的contextLoaded()方法。

11)调用ApplicationContext的refresh()方法,完成IoC容器可用的最后一道工序。

12)查找当前ApplicationContext中是否注册有CommandLineRunner,如果有,则遍历执行它们。

13)正常情况下,遍历执行SpringApplicationRunListener的finished ()方法、(如果整个过程出现异常,则依然调用所有SpringApplicationRunListener的finished()方法,只不过这种情况下会将异常信息一并传入处理)去除事件通知点后,整个流程如下:
在这里插入图片描述

六、Thymeleaf

SpringBoot官方不推荐使用JSP,官方推荐使用Thymeleaf。
Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与SpringMVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。

1、搭建示例工程

引入thymeleaf的包:
注意thymeleaf小版本之间的差异也可能比较大

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

在application.yml文件中配置thymeleaf的视图解析:

spring:
  mvc:
    view:
      suffix: .html
  thymeleaf:
    mode: LEGACYHTML5

controller代码

@RequestMapping("list.html")
    public String list(Model model){
        model.addAttribute("message","hello thymeleaf");
        return "list";
    }

页面写在/resources/templates 下
页面list.html,页面的文件名与controller中方法的返回值一致。 注意页面的<html>标签中有一个<html lang="en" xmlns:th="http://www.thymeleaf.org">

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<span th:text="${message}"></span>
</body>
</html>

页面中所有动态的内容都使用“th:”前缀。
并且在低版本thymeleaf的页面中,html语法要求很严格,比如标签必须闭合。如果要在解析时自动进行标签补全,需要引入iar包:

        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>
2、基础语法使用

使用文档:https://fanlychie.github.io/post/thymeleaf.html

spring-boot很多配置都有默认配置,比如默认页面映射路径为
classpath:/templates/* .html
同样css等静态文件路径为:classpath:/static/
在这里插入图片描述

1)、获取变量值

thymeleaf通过${变量名.属性名}来获取属性值,这个语法和EL表达式一样。
页面中所有动态的内容都使用“th:” 前缀,并且要写在标签中。text输出普通文本会转义标签内容,utext

<p th:text=${message}>this is tag p</p>

如果直接访问静态页面,会显示“this is tag p”
如果访问动态内容,那么${mesage}的值会替换掉原来<p>标签中的静态内容。

2)、遍历
<p th:each="d:${list}" th:text="${d.name}"></p>
3)、条件判断
<div th:if="${num==1}">
    <p th:each="d:${list}" th:text="${d.name}"></p>
</div>
4)、日期格式化

格式化日期

<span th:text="${#dates.format(today, 'yyyy-MM-dd HH:mm:ss')}"></span>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章