【精品】Spring Boot整合Mybatis,TkMybatis,Mybatis-Generator,PageHelper實際項目開發

近半年來,項目開發中一直使用Spring Boot、Spring Cloud等框架,開發工具由原來的eclispe轉用Idea ,哈哈,感覺自己又高大尚了一下,其中項目一些技術內容,使我們在開發中提高了開發效率。我一直想自己來搭建一套這樣的框架,可以工作之餘研究技術的時候,當做自己的一個項目進行編寫一些內容,來感受和學習技術在實際的項目中的應用。本文主要講述Spring Boot集成持久層相關的內容。相關的技術的內容,網絡上有很多講解內容,我主要是來把自己搭建的項目的具體代碼貼出來,方便大家參考,也能夠在本地按我的文章內容進行搭建,主要是在本地能夠把搭建的框架跑起來,好了,現在主要來貼一下相關的代碼:

首先我們來看一下我的項目目錄:

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.wzz</groupId>
    <artifactId>springbootpro</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
    </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>
        <!-- Spring Boot的核心啓動器,包含了自動配置、日誌和YAML -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!-- 支持全棧式Web開發,包括Tomcat和spring-webmvc -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- 支持面向方面的編程即AOP,包括spring-aop和AspectJ -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <!-- Mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- TkMybatis -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>

        <!-- 支持JDBC數據庫 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- 支持Redis鍵值存儲數據庫,包括spring-redis -->
<!--        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
        </dependency>-->

        <!-- 微信 -->
        <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-mp</artifactId>
            <version>3.1.0</version>
        </dependency>

        <!-- 企業微信 -->
        <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-cp</artifactId>
            <version>3.1.0</version>
        </dependency>

        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.12</version>
            <scope>provided</scope>
        </dependency>

        <!-- FastJson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
        </dependency>

        <!-- 圖形驗證碼生成工具 -->
        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>

        <!-- MySql驅動 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>5.1.47</version>
        </dependency>

        <!-- Mybatis分頁插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.1</version>
        </dependency>

    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/conf/generatorConfig.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.47</version>
                    </dependency>
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>3.5.0</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

2、application.properties 暫無配置內容

3、application.yml文件配置

#默認使用配置
spring:
  profiles:
    active: dev

mybatis:
  typeAliasesPackage: com.wzz.dao.model
  mapperLocations: classpath:com/wzz/dao/mapper/**/*.xml

mapper:
  mappers: com.wzz.dao.CommonMapper
  not-empty: false
  identity: MYSQL

#開發環境
---
spring:
  profiles: dev
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/site_web?useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
    username: admin
    password: admin

server:
  port: 9081
  servlet:
    context-path: /

wechat:
  openAppId: 
  openAppSecret: 

corpwechat:
  corpId: 
  corpSecret: 
  agentId: 

projecturl:
  wechatOpenAuthorize: 0.0.0.0:8080    
  cpwechatOpenAuthorize:

#測試環境
---
spring:
  profiles: test
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/site_web?useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
    username: admin
    password: admin

server:
  port: 9081
  servlet:
    context-path: /

wechat:
  openAppId: 
  openAppSecret: 

corpwechat:
  corpId: 
  corpSecret:
  agentId:

projecturl:
  wechatOpenAuthorize: 
  cpwechatOpenAuthorize:

4、generatorConfig.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="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="javaFileEncoding" value="UTF-8"/>
        <!-- 格式化java代碼 -->
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
        <!-- 格式化XML代碼 -->
        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>

        <!-- TKmybatis配置 -->
        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="com.wzz.dao.CommonMapper"/>
        </plugin>

        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="false"/>
        </commentGenerator>

        <!-- 數據庫鏈接URL、用戶名、密碼 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://10.3.2.17:3306/site_web"
                        userId="fof" password="JZ5]96qu8h59"/>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置 -->
        <javaModelGenerator targetPackage="com.wzz.dao.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成的映射文件包名和位置 -->
        <sqlMapGenerator targetPackage="com.wzz.dao.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成service的包名和位置 -->
        <javaClientGenerator targetPackage="com.wzz.dao.mapper" targetProject="src/main/java" type="XMLMAPPER">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!-- 要生成的那些表 -->
        <table tableName="tb_dictionary">
            <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
        </table>
    </context>

</generatorConfiguration>

5、MybatisConfig.java

package com.wzz.config;

import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * @Author wangzz
 * @Date 2019/2/21 18:21
 * @Description
 */
@Configuration
public class MybatisConfig {

    @Bean
    public PageHelper pageHelper(){
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("offsetAsPageNum","true");
        properties.setProperty("rowBoundsWithCount","true");
        properties.setProperty("reasonable","true");
        properties.setProperty("dialect","mysql");    //配置mysql數據庫的方言
        pageHelper.setProperties(properties);
        return pageHelper;
    }
}
6、Dao層目錄結構

CommonMapper.java
package com.wzz.dao;

import tk.mybatis.mapper.common.*;

/**
 * @Author wangzz
 * @Date 2019/2/21 16:27
 * @Description
 */
public interface CommonMapper<T> extends Mapper<T>, MySqlMapper<T>, IdsMapper<T>,ConditionMapper<T> {
}

我們使用mybatis-generator生成相關的dao層文件,示例如下:

TbDictionary.java
package com.wzz.dao.model;

import javax.persistence.*;

@Table(name = "tb_dictionary")
public class TbDictionary {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    /**
     * 字典編碼
     */
    private String code;

    /**
     * 名稱
     */
    private String name;

    /**
     * 類型
     */
    private String type;

    /**
     * 屬性標記
     */
    private String field;

    /**
     * 字典值
     */
    private String value;

    /**
     * 排序號
     */
    @Column(name = "sortCode")
    private Short sortcode;

    /**
     * 狀態:1可用,非1,不可用
     */
    private Byte status;

    /**
     * 備註
     */
    private String remark;

    /**
     * @return id
     */
    public Integer getId() {
        return id;
    }

    /**
     * @param id
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * 獲取字典編碼
     *
     * @return code - 字典編碼
     */
    public String getCode() {
        return code;
    }

    /**
     * 設置字典編碼
     *
     * @param code 字典編碼
     */
    public void setCode(String code) {
        this.code = code;
    }

    /**
     * 獲取名稱
     *
     * @return name - 名稱
     */
    public String getName() {
        return name;
    }

    /**
     * 設置名稱
     *
     * @param name 名稱
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 獲取類型
     *
     * @return type - 類型
     */
    public String getType() {
        return type;
    }

    /**
     * 設置類型
     *
     * @param type 類型
     */
    public void setType(String type) {
        this.type = type;
    }

    /**
     * 獲取屬性標記
     *
     * @return field - 屬性標記
     */
    public String getField() {
        return field;
    }

    /**
     * 設置屬性標記
     *
     * @param field 屬性標記
     */
    public void setField(String field) {
        this.field = field;
    }

    /**
     * 獲取字典值
     *
     * @return value - 字典值
     */
    public String getValue() {
        return value;
    }

    /**
     * 設置字典值
     *
     * @param value 字典值
     */
    public void setValue(String value) {
        this.value = value;
    }

    /**
     * 獲取排序號
     *
     * @return sortCode - 排序號
     */
    public Short getSortcode() {
        return sortcode;
    }

    /**
     * 設置排序號
     *
     * @param sortcode 排序號
     */
    public void setSortcode(Short sortcode) {
        this.sortcode = sortcode;
    }

    /**
     * 獲取狀態:1可用,非1,不可用
     *
     * @return status - 狀態:1可用,非1,不可用
     */
    public Byte getStatus() {
        return status;
    }

    /**
     * 設置狀態:1可用,非1,不可用
     *
     * @param status 狀態:1可用,非1,不可用
     */
    public void setStatus(Byte status) {
        this.status = status;
    }

    /**
     * 獲取備註
     *
     * @return remark - 備註
     */
    public String getRemark() {
        return remark;
    }

    /**
     * 設置備註
     *
     * @param remark 備註
     */
    public void setRemark(String remark) {
        this.remark = remark;
    }
}
TbDictionaryMapper.java
package com.wzz.dao.mapper;

import com.wzz.dao.CommonMapper;
import com.wzz.dao.model.TbDictionary;

public interface TbDictionaryMapper extends CommonMapper<TbDictionary> {
}

TbDictionaryMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wzz.dao.mapper.TbDictionaryMapper">
  <resultMap id="BaseResultMap" type="com.wzz.dao.model.TbDictionary">
    <!--
      WARNING - @mbg.generated
    -->
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="code" jdbcType="VARCHAR" property="code" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="type" jdbcType="VARCHAR" property="type" />
    <result column="field" jdbcType="VARCHAR" property="field" />
    <result column="value" jdbcType="VARCHAR" property="value" />
    <result column="sortCode" jdbcType="SMALLINT" property="sortcode" />
    <result column="status" jdbcType="TINYINT" property="status" />
    <result column="remark" jdbcType="VARCHAR" property="remark" />
  </resultMap>

</mapper>

7、程序進行調用看是否可以運行成功

首先看下啓動類

Application.java
package com.wzz;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@MapperScan("com.wzz.dao.mapper")
@Slf4j
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        log.info("------------------ SpringBoot應用啓動完成 ------------------");
    }
}
DictionaryService.java
package com.wzz.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wzz.dao.mapper.TbDictionaryMapper;
import com.wzz.dao.model.TbDictionary;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author wangzz
 * @Date 2019/2/21 17:33
 * @Description
 */
@Service
@Slf4j
public class DictionaryService {

    @Resource
    private TbDictionaryMapper tbDictionaryMapper;

    public List<TbDictionary>  queryList(){

        PageHelper.startPage(1,10);

        List<TbDictionary> dictList = tbDictionaryMapper.selectAll();

        log.info("---查詢結果---:{}",JSON.toJSON(dictList).toString());

        PageInfo<TbDictionary> pageInfo = new PageInfo<>(dictList);

        return pageInfo.getList();
    }


}
DictController.java
package com.wzz.controller;

import com.wzz.dao.model.TbDictionary;
import com.wzz.service.DictionaryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author wangzz
 * @Date 2019/2/21 17:36
 * @Description
 */
@RestController
@RequestMapping("/dict")
@Slf4j
public class DictController {

    @Autowired
    private DictionaryService dictionaryService;

    @GetMapping("/queryAll")
    @ResponseBody
    public List<TbDictionary> queryAll(){

        List<TbDictionary> dictList = dictionaryService.queryList();

        return  dictList;
    }
}

啓動程序日誌如下:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.2.RELEASE)

2019-02-21 18:59:33.163 [main] INFO  com.wzz.Application - Starting Application on DESKTOP-U2O7KPS with PID 11076 (F:\promotion\springbootpro\target\classes started by wangzhizhong in F:\promotion\springbootpro)
2019-02-21 18:59:33.163 [main] INFO  com.wzz.Application - The following profiles are active: dev
2019-02-21 18:59:33.883 [main] INFO  o.s.d.r.config.RepositoryConfigurationDelegate - Bootstrapping Spring Data repositories in DEFAULT mode.
2019-02-21 18:59:33.909 [main] INFO  o.s.d.r.config.RepositoryConfigurationDelegate - Finished Spring Data repository scanning in 23ms. Found 0 repository interfaces.
2019-02-21 18:59:34.318 [main] INFO  o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$2dfc831] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-02-21 18:59:34.666 [main] INFO  o.s.boot.web.embedded.tomcat.TomcatWebServer - Tomcat initialized with port(s): 9081 (http)
2019-02-21 18:59:34.688 [main] INFO  org.apache.coyote.http11.Http11NioProtocol - Initializing ProtocolHandler ["http-nio-9081"]
2019-02-21 18:59:34.704 [main] INFO  org.apache.catalina.core.StandardService - Starting service [Tomcat]
2019-02-21 18:59:34.704 [main] INFO  org.apache.catalina.core.StandardEngine - Starting Servlet engine: [Apache Tomcat/9.0.14]
2019-02-21 18:59:34.719 [main] INFO  org.apache.catalina.core.AprLifecycleListener - The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [D:\Program Files\Java\jdk1.8.0_65\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;D:\Program Files\Java\jdk1.7.0_17\bin;D:\Program Files\Java\jdk1.7.0_17\jre\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;D:\Program Files\IDM Computer Solutions\UltraEdit;D:\Program Files\OpenVPN\bin;D:\apache-maven-3.5.3\bin;D:\Program Files\nodejs\;D:\Program Files\erl10.1\bin;D:\Program Files\TortoiseSVN\bin;D:\Program Files\Python\Python36;C:\Users\wangzhizhong\AppData\Local\Microsoft\WindowsApps;C:\Users\wangzhizhong\AppData\Roaming\npm;D:\Program Files\nodejs\node_global;D:\Program Files\Fiddler;D:\Program Files\Microsoft VS Code Insiders\bin;.]
2019-02-21 18:59:34.936 [main] INFO  o.a.c.core.ContainerBase.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
2019-02-21 18:59:34.936 [main] INFO  org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 1704 ms
2019-02-21 18:59:35.105 [main] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
2019-02-21 18:59:35.437 [main] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
2019-02-21 18:59:35.521 [main] INFO  org.hibernate.jpa.internal.util.LogHelper - HHH000204: Processing PersistenceUnitInfo [
	name: default
	...]
2019-02-21 18:59:35.622 [main] INFO  org.hibernate.Version - HHH000412: Hibernate Core {5.3.7.Final}
2019-02-21 18:59:35.622 [main] INFO  org.hibernate.cfg.Environment - HHH000206: hibernate.properties not found
2019-02-21 18:59:35.769 [main] INFO  org.hibernate.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-02-21 18:59:35.891 [main] INFO  org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-02-21 18:59:36.053 [main] INFO  o.s.orm.jpa.LocalContainerEntityManagerFactoryBean - Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-02-21 18:59:36.553 [main] INFO  com.wzz.service.InitService - -----------PostConstruct執行初始化完成-----------
2019-02-21 18:59:36.753 [main] INFO  o.s.scheduling.concurrent.ThreadPoolTaskExecutor - Initializing ExecutorService 'applicationTaskExecutor'
2019-02-21 18:59:36.791 [main] WARN  o.s.b.a.o.j.JpaBaseConfiguration$JpaWebConfiguration$JpaWebMvcConfiguration - spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-02-21 18:59:36.991 [main] INFO  org.apache.coyote.http11.Http11NioProtocol - Starting ProtocolHandler ["http-nio-9081"]
2019-02-21 18:59:37.022 [main] INFO  o.s.boot.web.embedded.tomcat.TomcatWebServer - Tomcat started on port(s): 9081 (http) with context path ''
2019-02-21 18:59:37.022 [main] INFO  com.wzz.Application - Started Application in 4.307 seconds (JVM running for 5.265)
2019-02-21 18:59:37.091 [main] INFO  com.wzz.listener.CacheLoadExtExecutor - ---CacheLoadExtExecutor---:{"sourceArgs":[],"optionNames":[],"nonOptionArgs":[]}
2019-02-21 18:59:37.091 [main] INFO  com.wzz.listener.CacheLoadExtExecutor - -----------------ApplicationRunner開始執行初始化任務開始-----------------
2019-02-21 18:59:37.091 [main] INFO  com.wzz.listener.CacheLoadExtExecutor - -----------------ApplicationRunner開始執行初始化任務結束-----------------
2019-02-21 18:59:37.091 [main] INFO  com.wzz.listener.CacheLoadExecutor - ------------------CommandLineRunner開始執行初始化任務開始-------------------
2019-02-21 18:59:37.091 [main] INFO  com.wzz.listener.CacheLoadExecutor - ------------------CommandLineRunner開始執行初始化任務結束-------------------
2019-02-21 18:59:37.091 [main] INFO  com.wzz.Application - ------------------ SpringBoot應用啓動完成 ------------------

可以用postman進行調用接口,可以成功,接下來介紹點其他的小內容,在項目容器啓動完成後,可以進行初始化一些內容,可以藉助ApplicationRunner、CommandLineRunner來初始化。   PostConstruct是在Bean初始化完成後就進行執行了,一般使用前兩個更好一些。

來看一下代碼示例:

CacheLoadExecutor.java
package com.wzz.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * @Author wangzz
 * @Date 2019/2/21 9:14
 * @Description
 */
@Component
@Slf4j
public class CacheLoadExecutor implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        log.info("------------------CommandLineRunner開始執行初始化任務開始-------------------");
//        TimeUnit.SECONDS.sleep(3);
        log.info("------------------CommandLineRunner開始執行初始化任務結束-------------------");
    }
}
CacheLoadExtExecutor.java
package com.wzz.listener;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @Author wangzz
 * @Date 2019/2/21 9:28
 * @Description
 */
@Component
@Slf4j
public class CacheLoadExtExecutor implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("---CacheLoadExtExecutor---:{}", JSON.toJSON(args));
        log.info("-----------------ApplicationRunner開始執行初始化任務開始-----------------");
//        TimeUnit.SECONDS.sleep(3);
        log.info("-----------------ApplicationRunner開始執行初始化任務結束-----------------");

    }
}
package com.wzz.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @Author wangzz
 * @Date 2019/2/21 9:26
 * @Description
 */
@Service
@Slf4j
public class InitService {

    @PostConstruct
    public void init(){
        log.info("-----------PostConstruct執行初始化完成-----------");
    }
}

項目中,我們也可以配置一些AOP切面,來做一些打印日誌等一些操作,這個根據自己的項目需求來定,技術在此不講解,主要是貼代碼:

package com.wzz.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;

/**
 * 切面
 */
@Slf4j
@Aspect
@Component
public class AppLogAspect {

    // 定義一個切入點表達式,用來確定哪些類需要代理
    @Pointcut("execution(* com.wzz.controller..*.*(..))")
    public void cutMethod(){}

    // 環繞方法,可自定義目標方法執行的時機
    @Around("cutMethod()")
    public void around(ProceedingJoinPoint joinPoint){
        log.info("請求前 @Around :" + joinPoint.getSignature());
        try {
            joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        log.info("請求後 @Around :" + joinPoint.getSignature());

    }

    // 前置方法,在目標方法執行前執行
    @Before("cutMethod()")
    public void before(JoinPoint joinPoint) {
        log.info("請求前 @Before :" + joinPoint.getTarget());
    }

    // 定義通知類型
    @AfterReturning("cutMethod()")
    public void afterReturning(JoinPoint joinPoint) {
        log.info("請求後 @AfterReturning:" + joinPoint.getSignature());
    }

}

還有很多技術細節點,我們後面慢慢聊一下,感謝你的閱讀,大家一起努力,一起進步。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章