1. Create a project

Use idea You can quickly create SpringBoot The engineering of

Here, select the commonly used class library ,SpringBoot Encapsulate all kinds of framework class libraries , Can reduce the pom Reference configuration in file :

such as Spring and Mybatis When integrating , Tradition Spring The project needs to introduce :


And in the SpringBoot The introduction of :


You can see that in this class library, except mybatis and mybatis-spring outside , also spring-boot Things that are

complete pom.xml as follows :

<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
</properties> <dependencies>
</dependency> <dependency>
<!-- Use jsp page -->
</dependencies> <build>

The complete project path is as follows :

2. Entity classes and DAO

 public class Dept {
private Integer id;
private String name; //getter/setter Method brief

 public interface DeptDAO {
// Query list , The demo uses traditional mapper The mapping file
List<Dept> getDeltList();
// Insert , The demo is written with annotations sql, Omit xml To configure
@Insert("insert into DEPT(NAME) values(#{name})")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "ID")
void addDept(String name);


 <?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.springboot.ssm.dao.DeptDAO"> <resultMap id="deptMap" type="Dept">
<id property="id" column="ID"/>
<result property="name" column="NAME"/>
</resultMap> <select id="getDeltList" resultMap="deptMap">
select ID,NAME from DEPT


 public interface DeptService {
List<Dept> getDeltList();
void addDept(String name);

public class DeptServiceImpl implements DeptService {
private DeptDAO deptDAO; @Override
public List<Dept> getDeltList() {
return deptDAO.getDeltList();
} @Override
public void addDept(String name) {

4. Controller And page

public class DeptController {
private DeptService deptService; @RequestMapping("list.html")
public ModelAndView list() {
List<Dept> deptList = deptService.getDeltList();
return new ModelAndView("list", "deptList", deptList);
public String add(String name) {
// After adding successfully, redirect to the list page
return "redirect:list.html";


 <form action="/add.html" method="post">
Department name :<input type="text" name="name"/><br/>
<input type="submit" value="add"/>


 <c:forEach items="${deptList}" var="dept">

5. Start class

up to now , Projects and traditional spring It doesn't make any difference .

Tradition spring The following two configuration files need to be added to the project , and SpringBoot There is no configuration file in :

Tradition Spring There are the following files in the project :


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<!-- scanning @Service annotation -->
<context:component-scan base-package="com.test.springboot.ssm.service">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
<!-- Read configuration file -->
<context:property-placeholder location="classpath:db.properties" ignore-unresolvable="true"/>
<!-- Get the data source from the configuration file -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean> <!--spring management session factory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:com/test/springboot/ssm/dao/mapper/*.xml"/>
<!-- Configure entity class aliases -->
<property name="typeAliasesPackage" value="com.test.springboot.ssm.pojo"/>
</bean> <!-- Scan all mybatis Of dao Interface , Generate a proxy implementation class -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.test.springboot.ssm.dao"/>
</bean> <!-- Configure transaction manager -->
<bean id="transactionManager"
<property name="dataSource" ref="dataSource"/>
</bean> <!-- Transaction enhancement -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- Communication behavior , What matches is the method name -->
<tx:method name="add*" rollback-for="Exception"/>
<tx:method name="delete*" rollback-for="Exception"/>
<tx:method name="update*" rollback-for="Exception"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="do*" rollback-for="Exception"/>
</tx:advice> <!-- adopt AOP Configuration provides transaction enhancement , Give Way service Pack everything Bean All methods of have transactions -->
<aop:pointcut id="serviceMethod"
expression="execution(* com.test.springboot.ssm..*(..))"/>
<aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>
</aop:config> </beans>


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"> <mvc:annotation-driven/>
<!-- scanning Controller The bag where it is -->
<context:component-scan base-package="com.ssm.blog.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan> <!-- Configure the view parser -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property><!-- Prefix -->
<property name="suffix" value=".jsp"></property><!-- suffix -->
</bean> </beans>


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
<!-- To configure listener, Start up Web When loading a container Spring Configuration of -->
<!-- To configure DispatcherServlet -->

and SpringBoot You don't need these three profiles , Write a startup class , function main The method can :

@EnableTransactionManagement// Turn on transaction management
@ComponentScan("com.test.springboot.ssm")// Scan annotation elements
@MapperScan("com.test.springboot.ssm.dao")//Mybatis Of DAO Location package
public class SpringbootSsmApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootSsmApplication.class, args);
public static final String transactionExecution = "execution (* com.test.springboot.service..*(..))";
private DataSource dataSource;
// Declarative transactions
public DefaultPointcutAdvisor defaultPointcutAdvisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
Properties attributes = new Properties();
attributes.setProperty("get*", "PROPAGATION_REQUIRED,-Exception");
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);
return advisor;

Database and other configuration information application.properties in

 # Basic information about data sources 
spring.datasource.url = jdbc:mysql://localhost:3306/test?characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password =
spring.datasource.driverClassName = com.mysql.jdbc.Driver
#mybatis in mapper Path to file
# names . Can be omitted mybatis Of xml Medium resultType The full path of
#springMVC View information in , Response prefix
# Default suffix of response page
#DispatcherServlet In response to url-pattern

Just start the above program main Method to access .

in addition , If you need to package and publish to tomcat, You need to configure another ServletInitializer, otherwise tomcat After starting, it will appear 404.

 public class ServletInitializer extends SpringBootServletInitializer {
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringbootSsmApplication.class);

5. Start principle analysis

Any one of them SpringBoot Every program has a startup class :

public class StartApplication {
public static void main(String[] args) {
SpringApplication.run(StartApplication.class, args);

The startup class contains @SpringBootApplication Notes and SpringApplication.run() Method


@SpringBootApplication It's a composite annotation , In addition to the basic original information annotation , There are three important notes :




The following code is equivalent to using @SpringBootApplication annotation

public class StartApplication {
public static void main(String[] args) {
SpringApplication.run(StartApplication.class, args);

It's cumbersome to write three comments at a time , So use @SpringBootApplication More convenient .

5.1.1  @Configuration

To put it simply ,SpringBoot Use one @Configuration Class substitution of annotations xml The configuration file .

Such as spring-config.xml as follows :

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

SpringBoot It's written in Chinese :

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

If you define a bean,xml It's written in Chinese :

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

SpringBoot It's written in Chinese :

public Dept dept() {
Dept dept = new Dept();
return dept;
} @Bean
public Employee employee() {
Employee employee = new Employee();
employee.setDept(dept());// Inject dependency objects directly to call @Bean Method of annotation
return employee;

SpringBoot Use in @Bean Mark a method , The method name of this method will default to bean Of id. Be careful @Configuration Class to be @ComponentScan Scan to .

5.1.2 @ComponentScan

@ComponentScan Automatically scan and load components that conform to the rules . Can pass basePackages Specify packages to scan . If you don't specify a race second range ,SpringBoot Default will come from life @ComponentScan Scan the package of the class .

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

Equate to

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

5.5.3 @EnableAutoConfiguration

The purpose of this annotation is to automatically configure all bean Auto load to IoC Containers . For example, our project introduced spring-boot-starter-web rely on ,springboot Will automatically help us configure tomcat and springmvc.@EnableAutoConfigutation in @Import 了 EnableAutoConfigurationImportSelector,EnableAutoConfigurationImportSelector Class is used. Spring Core Bag SpringFactoriesLoader Class loadFactoryNamesof() Method . SpringFactoriesLoader Will inquire about META-INF/spring.factories The file contains JAR file .  When it finds spring.factories After the document ,SpringFactoriesLoader The properties named in the configuration file will be queried .spring.factories file , The contents are as follows :

5.2 SpringApplication

SpringApplication Of run The realization of this method is the main route of our journey , The main process of this method can be summarized as follows :

1) If we use SpringApplication Static run Method , that , The first step in this method is to create a SpringApplication Object instances , And then call this created. SpringApplication Instance method of . stay SpringApplication When the instance is initialized , It will do several things in advance :

a)  according to classpath Whether there is a feature class in it (org.springframework.web.context.ConfigurableWebApplicationContext) To determine whether a Web Applied ApplicationContext type .

b)  Use SpringFactoriesLoader In application classpath Find and load all available ApplicationContextInitializer.

c)  Use SpringFactoriesLoader In application classpath Find and load all available ApplicationListener.

d)  Infer and set main Method definition class .

2) SpringApplication After the instance initialization is completed and the settings are completed , We'll start run Method logic , Beginning of method implementation , First, traverse and execute all passes SpringFactoriesLoader Can be found and loaded SpringApplicationRunListener. Call their started() Method , Tell these SpringApplicationRunListener,“ well ,SpringBoot App to start !”.

3) Create and configure current Spring Boot What the app will use Environment( Include configuration to use PropertySource as well as Profile).

4) Traverse calls all SpringApplicationRunListener Of environmentPrepared() Methods , Tell them :“ At present SpringBoot Applied Environment Ready !”.

5) If SpringApplication Of showBanner Property is set to true, Then print banner.

6) According to whether the user has explicitly set applicationContextClass Type and the result of the initialization phase , Decide it should be current SpringBoot What kind of ApplicationContext And create it , Then decide whether to add or not according to the conditions ShutdownHook, Decide whether to use custom BeanNameGenerator, Decide whether to use custom ResourceLoader, Of course , The most important , We're going to have Environment Set to the created ApplicationContext Use .

7) ApplicationContext Once you've created it ,SpringApplication Will use Spring-FactoriesLoader, Find and load classpath All available in ApplicationContext-Initializer, Then iterate over and call these ApplicationContextInitializer Of initialize(applicationContext) Method to ApplicationContext Further processing .

8) Traverse calls all SpringApplicationRunListener Of contextPrepared() Method .

9) The core step , Pass before @EnableAutoConfiguration Get all the configuration and other forms of IoC The container configuration is loaded into the prepared ApplicationContext.

10) Traverse calls all SpringApplicationRunListener Of contextLoaded() Method .

11) call ApplicationContext Of refresh() Method , complete IoC Last process available for the container .

12) Find the current ApplicationContext Is there a CommandLineRunner, If there is , Then traverse and execute them .

13) Under normal circumstances , Traverse the execution SpringApplicationRunListener Of finished() Method 、( If the whole process is abnormal , Call all SpringApplicationRunListener Of finished() Method , In this case, the exception information will be passed in for processing )
After removing the event notification point , The whole process is as follows :

6. Thymeleaf

SpringBoot The official does not recommend the use of JSP, Official recommendation Thymeleaf.

Thymeleaf It's for rendering XML/XHTML/HTML5 Template engine for content . similar JSP,Velocity,FreeMaker etc. , It can also be easily associated with Spring MVC etc. Web The framework is integrated as Web Template engine for application . Compared with other template engines ,Thymeleaf The biggest feature is to be able to open and correctly display the template page directly in the browser , Without having to start the whole Web application .

6.1  Build a sample project

introduce thymeleaf My bag :


stay application.properties Configuration in file thymeleaf View resolution for :

spring.thymeleaf.mode =LEGACYHTML5
# Turn off caching during development , Otherwise, I can't see the real-time page
# Configure static resource paths

controller The code in is the same as in previous projects :

public String helloWorld(Model model) {
// Pass values to the page
model.addAttribute("welcome", "hello thymeleaf");
return "hello";

The page is written in /resources/templates Next

page hello.html, The file name of the page is the same as controller The return values of methods in are the same . Attention page <html> There is one in the label <html xmlns:th="http://www.thymeleaf.org">

 <!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<p th:text="${welcome}"></p>

All dynamic content on the page uses “th:” Prefix .

And in thymeleaf On the page of ,html The grammar is very strict , For example, the label must be closed . If you want to complete the label automatically during parsing , Need to introduce jar package :


6.2 Basic grammar

spring-boot Many configurations have default configurations , For example, the default page mapping path is
The same static file path is

First of all, the page <html> The label needs to be rewritten :

<html xmlns:th="http://www.thymeleaf.org">

6.2.1  Get the value of the variable

thymeleaf adopt ${ Variable name . Property name } To get the property value , This grammar and EL The expression is the same .

All dynamic content on the page uses “th:” Prefix , And write it in the label .

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

If you go directly to a static page , Will be displayed “this is tag p”

If you access dynamic content , that ${message} The value of will replace the original <p> Static content in tags .

Common page operations are as follows :

public String helloWorld(Model model) {
// Pass values to the page , Plain text
model.addAttribute("text", "hello thymeleaf");
//html Escape text
model.addAttribute("htmlText", "<h1>html</h1>");
model.addAttribute("ahref", "test");
List<String> list = new ArrayList<>();
model.addAttribute("list", list); List<Dept> deptList = new ArrayList<>();
deptList.add(new Dept(1, " Technology Department "));
deptList.add(new Dept(2, " Testing department "));
deptList.add(new Dept(3, " The administration department "));
model.addAttribute("deptList", deptList);
return "hello";
<p th:text="${text}"> I am the text </p>
<p th:utext="${htmlText}"> I'm an escape text </p>
<p><a th:href="@{{ahref}?pa={text}(ahref=${ahref},text=${text})}"> I am a a label </a></p>
I'm the form <br/>
<table border="1">
<tr th:each="dept:${deptList}">
<td th:text="${dept.id}">id</td>
<td th:text="${dept.name}">name</td>
I'm the drop-down box
<select >
<option th:each="dept:${deptList}" th:value="${dept.id}" th:text="${dept.name}" th:selected="${dept.id}==${param.id[0]}"></option>
<input th:value="${text}">
<script th:src="@{static/test.js}" type="text/javascript"></script>

6.2.2  conditional

 <div th:if="${ahref == 'test'}">xxxxxxx</div>

SpringBoot Integrate ssm More articles about

  1. Use SpringBoot Integrate ssm project

    SpringBoot What is it? ? Spring Boot By Pivotal A new framework from the team , It is designed to simplify the new Spring Initial setup and development of the application . Spring Boot Now it has become Java ...

  2. SpringBoot Integrate SSM( Code implementation Demo)

    SpringBoot Integrate SSM As shown in the figure : One . Data preparation : Database files : Database name :saas-export, Table name :ss_company Create table statement : DROP TABLE IF EXISTS ss_co ...

  3. Java learning SpringBoot Integrate SSM Demo

    background : stay Java Web in Spring The family has a very important position , Before JAVA Development requires a lot of configuration , A bunch of configuration files and deployment debugging has always been JavaWeb A big criticism in development , But now Spring Launched SpringBoot ...

  4. For the first time spring-boot Integrate ssm( There are many small pits )

    First , I use the official website to download , The best version is 1.5.16 Of ( That's the point ) After downloading , use idea Open the unzipped project . 1. Integrate spring-mvc stay pom.xml Add web rely on <dependency& ...

  5. Study SpringBoot Integrate SSM One of the three frameworks SpringBoot

    Spring Boot Source analysis One .Spring Boot Analysis of the start-up entry process of the project Spring Boot The entry point to the project main There is a... On the thread @SpringBootApplication( @Confi ...

  6. 【IDEA Filling pit 】springboot Integrate ssm frame

    Two problems : One is mybatis Unfamiliar   stay EmpMapper.xml In the definition of resultMap <resultMap id="EmpWithDept" type="c ...

  7. springboot Integrate mybatis,redis, Code ( One )

    One Set up the project , Code engineering structure Use idea perhaps sts structure springboot project Two   database sql sentence SQLyog Ultimate v12.08 (64 bit) MySQL - 5.7.14-l ...

  8. SpringBoot Integrate mybatis Use pageHelper The plug-in performs paging operations

    SpringBoot Integrate mybatis paging SpringBoot Integrate Mybatis Paging operations , You need to use Mybatis Pagination plug-in for :pageHelper, About pageHelper Introduction to , Please check out ...

  9. Quickly build springboot Framework and integration ssm+shiro+ install Rabbitmq and Erlang、Mysql Download and configure

    1. Quickly build springboot frame ( stay idea in ): file–>new project–>Spring Initializr–>next–> And then keep going . And then copy it ...

Random recommendation

  1. 【java Learning notes 】 String and Date Transformation

    String dateVal = "1992-12-06 18:34:23"; SimpleDateFormat sdf = new SimpleDateFormat(" ...

  2. scala learning :list span usage

    Pack consecutive duplicates of list elements into sublists. If a list contains repeated elements the ...

  3. Java The abnormal -Throwable-Error-Exception-RuntimeExcetpion-throw-throws-try catch

    Today I'm doing a project that will String Convert to Integer The function of the , Find out Integer.parseInte() It throws an exception NumberFormatException. function Integer.parseInt(Stri ...

  4. [Javascript] Intro to the Web Audio API

    An introduction to the Web Audio API. In this lesson, we cover creating an audio context and an osci ...

  5. [iOS common problem ] About use QQ Do the third party login problem !

    [iOS common problem ]  About use QQ Do the third party login problem ! Be careful :QQ There is no authorization function in itself , So I want to use QQ Third party login must be done through QQ Space to achieve ! First step : Integrate ShareSDK( The steps are the same as integration sharing , If integrated ...

  6. Realize password free input ssh Sign in

    Realize password free input ssh Login assumption A Machines for customers , B For the target machine : The purpose to achieve :A machine ssh Sign in B The machine doesn't have to enter a password : Choose the encryption method rsa|dsa All are OK , Default dsa practice :1. Sign in A machine 2 ...

  7. 5G arrival ,App The future of , yes JavaScript,Flutter still Native ?

    Native App React Native(RN) Published on 2015 year , Is also used JavaScript Language for cross platform APP Development of . And H5 Development is different from , It USES JS Bridge technology is compiled at run time into Nativ ...

  8. python Data analysis library pandas

    in my opinion , about Numpy as well as Matplotlib,Pandas Can help create a very solid foundation for data mining and Analysis . and Scipy( It will be mentioned in the next post ) Of course, it's another major and excellent library of Scientific Computing , But I ...

  9. [LeetCode] 824. Goat Latin_Easy

    A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and up ...

  10. About Unity Rigid bodies and colliders in ( Two )

    In relation to Unity Rigid bodies and colliders in ( One ) On the basis of There is one plane Plane , One ball sphere , It's all jammed ,ball Hang up Rigidbody, I wrote a script ball Mounted on a sphere , The ball falls from the air and is loaded ...