Spring Boot + MySQL + MyBatis + Maven + Logging + Thymeleaf 项目搭建、配置、运行、部署完整教程

1. 创建一个springboot应用

1.1 创建

  springboot应用没有相应的archetype,不能通过mvn generate:archetype创建,一般有两种方式创建一个springboot应用:

  • 访问 https://start.spring.io/,选择Web依赖,点击Generate Project 创建一个springboot应用。
  • 通过IDEA:File -> New Project -> Spring Initializr -> Choose Initializr Service URL(https://start.spring.io) -> next(填写 Project Metadata) -> next -> 选择Web -> Finish

1.2 启动

mvn spring-boot:run
# 或
mvn clean spring-boot:run

1.3 @SpringBootApplication

  @SpringBootApplicatoin是用的@ComponentScan扫描,扫描的是Component,包括@Component, @Controller, @Service, @Repository等。

  SpringBootApplication默认扫描运行类所在包及其子包中的Component

2. 单元测试

2.1 spring-boot-starter-test Starter

  通常通过添加 spring-boot-starter-test "Starter"依赖来导入 Spring Boot test 模块以及 JUnit, AssertJ, Hamcrest, Spring Test, Mockito, JSONassert and JSONPath 库,如果这些库满足不了你的需要,你可以再添加其他的测试依赖。

        <!-- spring-boot-starter-test imports both Spring Boot test modules as well as JUnit, AssertJ, Hamcrest, Spring Test, Mockito, JSONassert and JSONPath -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

2.2 @SpringBootTest

A Spring Boot application is a Spring ApplicationContext, so nothing very special has to be done to test it beyond what you would normally do with a vanilla Spring context.

Spring Boot provides a @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext used in your tests through SpringApplication.

3. 集成MyBatis

3.1 pom.xml中添加MyBatis依赖

        <!-- mybatis ORM 框架 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
            <scope>runtime</scope>
        </dependency>

        <!-- Druid 数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.29</version>
        </dependency>

3.2 application.properties中添加相关配置

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/erp?autoReconnect=true&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# \u521D\u59CB\u5316\u5927\u5C0F\uFF0C\u6700\u5C0F\uFF0C\u6700\u5927
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# \u914D\u7F6E\u83B7\u53D6\u8FDE\u63A5\u7B49\u5F85\u8D85\u65F6\u7684\u65F6\u95F4
spring.datasource.maxWait=60000

# mybatis
mybatis.mapper-locations=classpath*:mapping/*.xml
mybatis.type-aliases-package=net.mrliuli.erp.domain.entity

3.3 添加mybatis-generator插件

3.3.1 pom.xml中添加插件
            <!-- Mybatis Generator 插件 =================================================== -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <dependencies>
                    <!-- 数据库驱动 -->
                    <!-- 如果不在此声明这个依赖,可以在 mybatis-generator.xml中通过<classPathEntry><classPathEntry>添加 -->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.35</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <!-- 允许移动生成的文件 -->
                    <verbose>true</verbose>
                    <!-- 是否覆盖 -->
                    <overwrite>true</overwrite>
                    <!-- 自动生成的配置 -->
                    <configurationFile>
                        src/main/resources/mybatis-generator.xml
                    </configurationFile>
                </configuration>
            </plugin>
            <!-- =================================================== Mybatis Generator 插件 -->
3.3.2 添加mybatis-generator配置文件src/main/resources/mybatis-generator.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    
    <context id="erp" targetRuntime="MyBatis3">

        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--数据库链接地址账号密码-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/erp"
                        userId="root"
                        password="123456">
        </jdbcConnection>

        <!-- 默认false:把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer; true:把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 生成Entity实体类存放位置 -->
        <javaModelGenerator targetPackage="net.mrliuli.erp.domain.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--生成映射文件存放位置-->
        <sqlMapGenerator targetPackage="net.mrliuli.erp.mapping" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!--生成Dao类(接口)存放位置-->
        <!-- 客户端代码,生成易于使用的针对Entity对象和XML配置文件 的代码
                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
        -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="net.mrliuli.erp.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!--生成对应表及类名-->
        <table tableName="t_sales_order" domainObjectName="SalesOrder"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>
    </context>
    
</generatorConfiguration>
3.3.3 修改配置文件
# mybatis
# mapper-locations 的目录结构要用斜杠形式,不能用点!
mybatis.mapper-locations=classpath*:net/mrliuli/erp/mapping/*.xml
mybatis.type-aliases-package=net.mrliuli.erp.domain.entity
3.3.4 运行插件
mvn mybatis-generator:generate

4. 开发者工具spring-boot-devtools 实现热部署方便调试

  spring-boot-devtools 用于实现热交换,开发者添加该依赖后,当类路径下的类有更改时,不需要手动重启,即可实现类的更新替换。

4.1 首先在pom.xml中添加依赖:

        <!-- 开发人员工具 -->
        <!-- 运行打包的应用程序时,开发人员工具会自动禁用。如果你通过 java -jar或者其他特殊的类加载器进行启动时,都会被认为是“生产环境的应用”。 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <!-- optional=true,依赖不会传递,该项目依赖devtools;之后依赖该项目的项目如果想要使用devtools,需要重新引入 -->
            <optional>true</optional>
        </dependency>

4.2 配置IntellJ IDEA以使其触发spring-boot-devtools

 “File” -> “Settings” -> “Build,Execution,Deplyment” -> “Compiler”,选中打勾 “Build project automatically” 。

4.3 Chrome禁用缓存

F12,打开开发者工具,“Network” 选项卡下 选中打勾 “Disable Cache(while DevTools is open)” 

5. 打包与部署

  对于spring-boot web应用,因其内嵌有servlet容器,所以有两种打包方式:一是打成jar包,直接执行,另一种就是传统方式,打成war包放到tomcat下执行。

  • 打成jar包
# cd到项目根目录
mvn clean package

# 直接执行
java -jar  target/spring-boot-scheduler-1.0.0.jar
  • 打成可部署的war包(即传统方式,注意不支持WebFlux应用),使用非内嵌tomcat

    • Step 1:提供一个SpringBootServletInitializer的子类并重写configure方法。
        如此做的目的是使用Spring Framework’s Servlet 3.0支持,当servlet容器启动的时候,来配置你的应用。通常是将Application类继承SpringBootServletInitializer,如下:
    @SpringBootApplication
    public class Application extends SpringBootServletInitializer {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
    
        }
    
        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(Application.class);
        }
    
    }
    
    • Step 2:修改pom.xml打包方式为war
    <packaging>war</packaging>
    
    • Step 3:解决内嵌的servlet容器与部署warservlet容器之间的冲突。只需将内嵌的servlet容器的依赖scope标记为provided,如下(该项目是tomcat):
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
    
    • Step 4:打包运行:
    # cd到项目根目录
    mvn clean package
    
    # 复制`target/erp-0.0.1-SNAPSHOT.war`到`%TOMCAT_HOME%/webapps/`下,启动tomcat执行。
    浏览器输入 `http://localhost:8080/erp-0.0.1-SNAPSHOT/` 测试
    

6. 多环境配置(开发、测试、UAT、生产)

  Spring Boot也是通过profile来实现多环境配置的。

6.1 添加application-{profile}.properties文件

  多环境配置文件名需要满足格式application-{profile}.properties,注意application{profile}之间是短杠

PC@P0005 MINGW64 /d/program/sa/erp/src/main/resources (master)
$ ll
total 12
-rw-r--r-- 1 PC 197121  675 五月  3 10:10 application.properties
-rw-r--r-- 1 PC 197121  274 五月  3 10:00 application-dev.properties
-rw-r--r-- 1 PC 197121  274 五月  3 10:01 application-release.properties
-rw-r--r-- 1 PC 197121  272 五月  3 10:01 application-test.properties
-rw-r--r-- 1 PC 197121  274 五月  3 10:01 application-uat.properties

6.2 修改spring.profiles.active属性

  在application.properties文件中修改spring.profiles.active属性的值,如:

# PROFILES
# Comma-separated list of active profiles. Can be overridden by a command line switch.
spring.profiles.active=dev

6.3 命令行启动设置配置参数

  启动时设置8081端口,设置使用application-dev.properties配置文件。

java -jar target/spring-boot-scheduler-1.0.0.jar --port=8081 --spring.profiles.active=dev

7. json接口开发

  传统的Spring开发中,要返回json格式,需要添加jackson等相关jar包,配置spring controller扫描,以及在对应的方法上添加@ResponseBody
  对于Spring Boot只需要类添加@RestController,则默认类中的方法都会以json的格式返回
  只要返回的类型能被Jackson2序列化(对于POJO或Groovy对象总是可以序列化)。Note that, in a browser, you might sometimes see XML responses, because browsers tend to send accept headers that prefer XML.

8. HTML页面与Thymeleaf模板引擎

  SpringBoot应用是没有webapp目录的。

Do not use the src/main/webapp directory if your application is packaged as a jar. Although this directory is a common standard, it works only with war packaging, and it is silently ignored by most build tools if you generate a jar.

8.1 静态内容

  •   默认,Spring Boot从类路径或ServletContext根路径的如下目录中加载静态内容:
/static
/public
/resources
/META-INF/resources
  •   Spring Boot使用Spring MVCResourceHttpRequestHandler来处理静态内容。
  •   默认,资源映射到/**,可以通过如下属性改变映射,如:
spring.mvc.static-path-pattern=/resources/**
8.1.1 欢迎页面(Welcome Page)

Spring Boot supports both static and templated welcome pages. It first looks for an index.html file in the configured static content locations. If one is not found, it then looks for an index template. If either is found, it is automatically used as the welcome page of the application.

  以上是官网的介绍,但经过测试,实际并不是如上所述,测试的结果是:

  • 首先寻找"/"RequestMapping所映射的模板面面。
  • 然后再从静态资源路径下寻找index.html
8.1.2 自定义应用图标(Custom Facicon)

Spring Boot looks for a favicon.ico in the configured static content locations and the root of the classpath (in that order). If such a file is present, it is automatically used as the favicon of the application.

8.2 动态HTML内容(使用Themeleaf模板引擎)

  Spring Boot建议不使用JSP,建议使用Themeleaf来做动态页面。

  • 添加Themeleaf依赖。
<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-thymeleaf</artifactId> 
</dependency>
  • Spring Boot 使用Themeleaf模板引擎时,默认配置自动从src/main/resources/templates路径加载模板文件。
/**
 * 需要返回页面,则不能使用`@RestController`(会将返回值转换成`JSON`)!
 */
@Controller
public class HomeController {

    @RequestMapping("/")
    public String index(HttpServletRequest request){
        request.setAttribute("key", "welcome, this is a dynamic page!");
        /**
         * Spring Boot 使用`Thymeleaf`模板引擎默认从`src/main/resources/templates`加载动态页面,
         * 所以,这里将跳转到`templates/index.html`动态页面。
         */
        return "index";
    }

}

9. Logging

SLF4J——Simple Logging Facade For Java,它是一个针对于各类Java日志框架的统一Facade抽象。Java日志框架众多——常用的有java.util.logging, log4j, logback,commons-logging, Spring框架使用的是Jakarta Commons Logging API (JCL)。而SLF4J定义了统一的日志抽象接口,而真正的日志实现则是在运行时决定的——它提供了各类日志框架的binding。

  Spring Boot在所有内部日志中使用Commons Logging,即Spring Boot框架使用的是Commons Logging
  默认情况下,Spring Boot应用使用Logback记录日志,并用INFO级别输出到控制台

9.1 日志格式

2014-03-05 10:57:51.112  INFO 45469 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.52
2014-03-05 10:57:51.253  INFO 45469 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2014-03-05 10:57:51.253  INFO 45469 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1358 ms
2014-03-05 10:57:51.698  INFO 45469 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2014-03-05 10:57:51.702  INFO 45469 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]

  具体元素如下:

  • 时间日期:精确到毫秒
  • 日志级别:ERROR, WARN, INFO, DEBUG or TRACE
  • 进程ID
  • 分隔符:--- 标识实际日志的开始
  • 线程名:方括号括起来(可能会截断控制台输出)
  • Logger名:通常使用源代码的类名
  • 日志内容

Logback does not have a FATAL level. It is mapped to ERROR.

9.2 输出级别

  日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL,Spring Boot中默认配置ERRORWARNINFO级别的日志输出到控制台。
  配置DEBUG输出级别,两种方式:

  • $ java -jar myapp.jar --debug
  • application.properties 中配置 debug=true。该属性置为true的时候,核心Logger(包含嵌入式容器、hibernate、spring)会输出更多内容,但是自己应用的日志并不会输出为DEBUG级别。

  另外,也可以通过启用trace模式来输出TRACE级别日志,如 starting your application with a --trace flag (or trace=true in your application.properties)。

All the supported logging systems can have the logger levels set in the Spring Environment (for example, in application.properties) by using logging.level.= where level is one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL, or OFF. The root logger can be configured by using logging.level.root.

The following example shows potential logging settings in application.properties:

logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR

9.3 文件输出

By default, Spring Boot logs only to the console and does not write log files. If you want to write log files in addition to the console output, you need to set a logging.file or logging.path property (for example, in your application.properties).

  • logging.file,设置文件,可以是绝对路径,也可以是相对路径。如:logging.file=my.log
  • logging.path,设置目录,会在该目录下创建spring.log文件,并写入日志内容,如:logging.path=/var/log

  如果只配置 logging.file,会在项目的当前路径下生成一个 xxx.log 日志文件。
如果只配置 logging.path,在 /var/log 文件夹生成一个日志文件为 spring.log

注:二者不能同时使用,如若同时使用,则只有logging.file生效

9.4 自定义日志配置

Since logging is initialized before the ApplicationContext is created, it is not possible to control logging from @PropertySources in Spring @Configuration files. The only way to change the logging system or disable it entirely is via System properties.

  根据不同的日志系统,如下规则组织配置文件名,就能被正确加载:

Logging System 日志系统Customization 自定义日志配置文件名
Logbacklogback-spring.xml, logback-spring.groovy, logback.xml, or logback.groovy

When possible, we recommend that you use the -spring variants for your logging configuration (for example, logback-spring.xml rather than logback.xml). If you use standard configuration locations, Spring cannot completely control log initialization.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值