認識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>