SpringBoot進階教程(六十一)intellij idea project下建多個module搭建架構(下)

来源:https://www.cnblogs.com/toutou/archive/2019/08/25/project_module_2.html
-Advertisement-
Play Games

在上一篇文章《SpringBoot進階教程(六十)intellij idea project下建多個module(上)》中,我們已經介紹了在intellij idea中創建project之後再分化多個module,今天再大致介紹介紹各個module之間詳細工作的細分。 如果是不考慮細分多個modul... ...


在上一篇文章《SpringBoot進階教程(六十)intellij idea project下建多個module(上)》中,我們已經介紹了在intellij idea中創建project之後再分化多個module,今天再大致介紹介紹各個module之間詳細工作的細分。 如果是不考慮細分多個module的話,可以看看這篇文章《SpringBoot入門教程(一)詳解intellij idea搭建SpringBoot》。

v設計資料庫

CREATE TABLE `useraccount` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `username` varchar(255) NOT NULL,
    `age` int(10) NOT NULL,
    `phone` bigint NOT NULL,
    `email` varchar(255) NOT NULL,
    `account` varchar(100) NOT NULL UNIQUE,
    `pwd` varchar(255) NOT NULL,
    PRIMARY KEY (`id`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
insert into `useraccount` values(1,'趙(dev)',23,158,'[email protected]','test001','test001');
insert into `useraccount` values(2,'錢(dev)',27,136,'[email protected]','test002','test002');
insert into `useraccount` values(3,'孫(dev)',31,159,'[email protected]','test003','test003');
insert into `useraccount` values(4,'李(dev)',35,130,'[email protected]','test004','test004');
select * from `useraccount`;

v引入mybatis

1.0 添加mybatis插件

在learn-persist的pom.xml中添加mybatis插件。

<build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>${mybatis-generator.version}</version>
                <dependencies>
                    <dependency>
                        <groupId> mysql</groupId>
                        <artifactId> mysql-connector-java</artifactId>
                        <version>${mysql.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>${mybatis-generator.version}</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <!-- 自動生成的配置 -->
                    <configurationFile>src/main/resources/mybatis-config/mybatis-generator.xml</configurationFile>
                    <!--允許移動生成的文件 -->
                    <verbose>true</verbose>
                    <!-- 是否覆蓋 -->
                    <overwrite>false</overwrite>
                </configuration>
            </plugin>
        </plugins>
    </build>

SpringBoot進階教程(六十一)intellij idea project下建多個module搭建架構(下)

如上圖,在learn-persist的resources下分別創建mapper和mybatis-config文件目錄,並添加jdbc.properties和mybatis-generator.xml文件。

1.1 jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mytest?useSSL=false
jdbc.username=toutou
jdbc.password=demo123456

1.2 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>
    <properties resource="mybatis-config/jdbc.properties"/>
    <context id="DB2Tables"    targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--資料庫鏈接地址賬號密碼-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <javaModelGenerator targetPackage="learn.model.po"
                            targetProject="../learn-model/src/main/java/">
            <property name="enableSubPackages" value="false" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="mapper"
                         targetProject="../learn-persist/src/main/resources">
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <javaClientGenerator targetPackage="learn.persist"
                             targetProject="../learn-persist/src/main/java/"
                             type="XMLMAPPER">
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!--生成對應表及類名-->
        <table tableName="useraccount" domainObjectName="UserAccount" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

mybatis-generator.xml更多介紹可以看這裡

1.3 版本號統一配置

SpringBoot進階教程(六十一)intellij idea project下建多個module搭建架構(下)

為了方便後續管理,將所有引入插件的版本號統一放在project(hellolearn)的pom.xml中統一控制,各子module(如learn-persist)的pom.xml中直接用 ${} 的方法使用。

例如:在hellolearn的pom.xml 屬性中添加 < mybatis-generator.version>1.3.6< /mybatis-generator.version> ,在learn-persist的pom.xml中直接 < version>${mybatis-generator.version}< /version> 使用即可。

註意上面的"例如"中代碼標簽部分有空格是為了轉義的,防止瀏覽器將"mybatis-generator.version"和"version"識別為html標簽。

1.4 Maven Project 插件

SpringBoot進階教程(六十一)intellij idea project下建多個module搭建架構(下)

如上圖,在idea右側的maven project中就可以了對應的找到mybatis-generator的插件,如果找不到就右鍵maven project中的learn-persist,然後點擊generate sources...。

1.5 運行mybatis generator插件

SpringBoot進階教程(六十一)intellij idea project下建多個module搭建架構(下)

如上圖,點擊運行mybatis generator:generator插件,會對應生成左側標紅的三個文件。

v編寫controller

2.0 添加result返回實體類

package learn.model.vo;

import java.io.Serializable;

/**
 * @author toutou
 * @date by 2019/07
 */
public class Result<T> implements Serializable {

    public int code;
    public String message;
    public T data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public static <T> Result<T> setSuccessResult(T t){
        Result<T> r = new Result<T>();
        r.setCode(200);
        r.setData(t);
        r.setMessage("success");
        return r;
    }

    public static <T> Result<T> setErrorResult(int tempCode, String messageTemp){
        Result<T> r = new Result<T>();
        r.setCode(tempCode);
        r.setMessage(messageTemp);
        return r;
    }
}

2.1 添加controller

SpringBoot進階教程(六十一)intellij idea project下建多個module搭建架構(下)

package learn.web.controller;

import learn.model.vo.Result;
import learn.model.vo.UserAccountVO;
import learn.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author toutou
 * @date by 2019/07
 */
@RestController
public class UserController {

    @Autowired
    UserAccountService userAccountService;

    @GetMapping("/user/hello")
    public String helloWorld() {
        return "hello world.";
    }

    @GetMapping("/user/getuser")
    public Result getUserAccountById(@RequestParam("uid") int id){
        UserAccountVO user = userAccountService.getUserAccountById(id);
        if(user != null){
            return Result.setSuccessResult(user);
        }else{
            return Result.setErrorResult(404, "用戶不存在");
        }
    }
}
註意:getUserAccountById暫時用不上,可以先不添加。

2.2 添加aplication啟動類

package learn.web;

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

/**
 * Created by toutou on 2019/7
 */
@SpringBootApplication
@ComponentScan(basePackages = {"learn.*" })
@MapperScan(basePackages = {"learn.persist"})
public class Application {

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

}

 

2.3 添加aplication.properties

server.port=8300
spring.profiles.active=@env@

#mybatis
mybatis.mapper-locations = classpath:mapper/*Mapper.xml

2.4 配置啟動類

SpringBoot進階教程(六十一)intellij idea project下建多個module搭建架構(下)

2.5 測試效果

SpringBoot進階教程(六十一)intellij idea project下建多個module搭建架構(下)

v編寫service

3.1 添加Service

package learn.service;

import learn.model.vo.UserAccountVO;

/**
 * @author toutou
 * @date by 2019/07
 */
public interface UserAccountService {
    UserAccountVO getUserAccountById(Integer id);
}

3.2 實現Service

package learn.service.impl;

import learn.model.po.UserAccount;
import learn.model.vo.UserAccountVO;
import learn.persist.UserAccountMapper;
import learn.service.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author toutou
 * @date by 2019/07
 */
@Service
public class UserAccountServiceImpl implements UserAccountService{
    @Autowired
    UserAccountMapper userMapper;

    public UserAccountVO getUserAccountById(Integer id){
        UserAccountVO accountVO = null;
        UserAccount account = userMapper.selectByPrimaryKey(id);
        if (account != null) {
            accountVO = new UserAccountVO();
            accountVO.setId(account.getId());
            accountVO.setAccount(account.getAccount());
            accountVO.setAge(account.getAge());
            accountVO.setEmail(account.getEmail());
            accountVO.setUsername(account.getUsername());
            accountVO.setPhone(account.getPhone());
        }

        return accountVO;
    }
}

v配置設置

4.1 添加application.properties

SpringBoot進階教程(六十一)intellij idea project下建多個module搭建架構(下)

4.2 添加application.dev.properties

spring.datasource.url=jdbc:mysql://localhost:3306/mytest?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2b8
spring.datasource.username=toutou
spring.datasource.password=demo123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

4.3 添加pom.xml配置

4.3.1 hellolearn pom.xml

SpringBoot進階教程(六十一)intellij idea project下建多個module搭建架構(下)

4.3.2 learn-web pom.xml

    <build>
        <filters>
            <filter>src/main/resources/config/application-${env}.properties</filter>
        </filters>
    </build>

4.4 更新application啟動類

SpringBoot進階教程(六十一)intellij idea project下建多個module搭建架構(下)

4.5 測試效果

SpringBoot進階教程(六十一)intellij idea project下建多個module搭建架構(下)

vlinux部署springboot

5.1 learn-web pom.xml中添加插件

    <build>
        <filters>
            <filter>src/main/resources/config/application-${env}.properties</filter>
        </filters>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>learn.web.Application</mainClass>
                    <classifier>exec</classifier>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

5.2 hellolearn pom.xml中添加插件

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <excludes>
                        <exclude>**/profiles/</exclude>
                        <exclude>**/mybatis-generator/</exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

註意:如果有用到profiles文件目錄則exclude。

5.3 打包部署

SpringBoot進階教程(六十一)intellij idea project下建多個module搭建架構(下)

java -jar learn-web-0.0.1-SNAPSHOT-exec.jar --server.port=95

SpringBoot進階教程(六十一)intellij idea project下建多個module搭建架構(下)

你可能會遇到的問題:

v源碼地址

https://github.com/toutouge/javademosecond/tree/master/hellolearn


作  者:請叫我頭頭哥
出  處:http://www.cnblogs.com/toutou/
關於作者:專註於基礎平臺的項目開發。如有問題或建議,請多多賜教!
版權聲明:本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接。
特此聲明:所有評論和私信都會在第一時間回覆。也歡迎園子的大大們指正錯誤,共同進步。或者直接私信
聲援博主:如果您覺得文章對您有幫助,可以點擊文章右下角推薦一下。您的鼓勵是作者堅持原創和持續寫作的最大動力!


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1.add添加 2.discard刪除 3.update批量添加 4.intersection取交集 5.union取並集 6.difference取差集 7.symmetric_difference對稱差集 ...
  • 說,我有一個需求,就是一個臨時功能。由於工作開發問題,我們有一個B項目,需要有一個商品添加的功能,涉及到添加商品內容,比如商品名字,商品描述,商品庫存,商品圖片等。後臺商品添加的介面已經寫完了,但是問題是目前沒有後臺頁面,就是產品還沒有出後臺詳細頁面。前端已經完備了,上線了。後臺還需要工作時間處理。 ...
  • SpringBoot預設使用Tomcat作為嵌入式的Servlet容器; 1、如何定製和修改Servlet容器的相關配置; 1、修改和server有關的配置(ServerProperties【也是EmbeddedServletContainerCustomizer】); 2、編寫一個Embedded ...
  • 說起應用分層,大部分人都會認為這個不是很簡單嘛 就`Controller`,`Service`, `Mapper`三層。看起來簡單,很多人其實並沒有把他們職責劃分開,在很多代碼中,`Controller`做的邏輯比`Service`還多,`Service`往往當成透傳了,這其實是很多人開發代碼都沒有... ...
  • 新聞 "高效的F ,提示與技巧" "Fable 社區資源" "Visual Studio提示與技巧:為.NET增加生產力" "無風險地嘗試Compositional IT的培訓包——如果沒有增加任何價值,可以得到完全退款" ".NET Core與systemd" "在Visual Studio中通過 ...
  • 2019/08/25 1、eclipse 程式安裝 https://www.cnblogs.com/tianxxl/p/10043390.html 網盤路徑:JAVA學習文件 2、資源文件 https://www.cnblogs.com/litexy/p/9746755.html ...
  • 痛苦而艱難 才寫出這一點點,這是個登陸測試 main 抓包類login_tst 剛學測試和python 寫的一般 讓各位見笑了 ...
  • 1.位元組流: FileInputStream(位元組輸入流) 特有方法: FileInputStream fis = new FileInputStream("temp.txt"); 1.int num = fis.available();//返迴文件的位元組總個數 2.fis.read()//返回in ...
一周排行
    -Advertisement-
    Play Games
  • 基於.NET Framework 4.8 開發的深度學習模型部署測試平臺,提供了YOLO框架的主流系列模型,包括YOLOv8~v9,以及其系列下的Det、Seg、Pose、Obb、Cls等應用場景,同時支持圖像與視頻檢測。模型部署引擎使用的是OpenVINO™、TensorRT、ONNX runti... ...
  • 十年沉澱,重啟開發之路 十年前,我沉浸在開發的海洋中,每日與代碼為伍,與演算法共舞。那時的我,滿懷激情,對技術的追求近乎狂熱。然而,隨著歲月的流逝,生活的忙碌逐漸占據了我的大部分時間,讓我無暇顧及技術的沉澱與積累。 十年間,我經歷了職業生涯的起伏和變遷。從初出茅廬的菜鳥到逐漸嶄露頭角的開發者,我見證了 ...
  • C# 是一種簡單、現代、面向對象和類型安全的編程語言。.NET 是由 Microsoft 創建的開發平臺,平臺包含了語言規範、工具、運行,支持開發各種應用,如Web、移動、桌面等。.NET框架有多個實現,如.NET Framework、.NET Core(及後續的.NET 5+版本),以及社區版本M... ...
  • 前言 本文介紹瞭如何使用三菱提供的MX Component插件實現對三菱PLC軟元件數據的讀寫,記錄了使用電腦模擬,模擬PLC,直至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1. PLC開發編程環境GX Works2,GX Works2下載鏈接 https:// ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • 1、jQuery介紹 jQuery是什麼 jQuery是一個快速、簡潔的JavaScript框架,是繼Prototype之後又一個優秀的JavaScript代碼庫(或JavaScript框架)。jQuery設計的宗旨是“write Less,Do More”,即倡導寫更少的代碼,做更多的事情。它封裝 ...
  • 前言 之前的文章把js引擎(aardio封裝庫) 微軟開源的js引擎(ChakraCore))寫好了,這篇文章整點js代碼來測一下bug。測試網站:https://fanyi.youdao.com/index.html#/ 逆向思路 逆向思路可以看有道翻譯js逆向(MD5加密,AES加密)附完整源碼 ...
  • 引言 現代的操作系統(Windows,Linux,Mac OS)等都可以同時打開多個軟體(任務),這些軟體在我們的感知上是同時運行的,例如我們可以一邊瀏覽網頁,一邊聽音樂。而CPU執行代碼同一時間只能執行一條,但即使我們的電腦是單核CPU也可以同時運行多個任務,如下圖所示,這是因為我們的 CPU 的 ...
  • 掌握使用Python進行文本英文統計的基本方法,並瞭解如何進一步優化和擴展這些方法,以應對更複雜的文本分析任務。 ...
  • 背景 Redis多數據源常見的場景: 分區數據處理:當數據量增長時,單個Redis實例可能無法處理所有的數據。通過使用多個Redis數據源,可以將數據分區存儲在不同的實例中,使得數據處理更加高效。 多租戶應用程式:對於多租戶應用程式,每個租戶可以擁有自己的Redis數據源,以確保數據隔離和安全性。 ...