共计 30066 个字符,预计需要花费 76 分钟才能阅读完成。
前言
🍊原因
常常看到网上很多 优良的开源我的项目中,代码简洁,模块分层完满 。反观本人代码层级凌乱,,却不知如何整顿分层。此文 手把手教你一步一步创立模块 ,左手右手一个慢动作。联合自己理论开发及集体我的项目中 分层思路的分享,大神请勿喷。
⏲️本文浏览时长
约 25 分钟
🎯次要指标
- 熟练掌握 SpringBoot 我的项目分层思路,丝滑拆分模块
- 相熟代码层级依赖,规范化治理模块散布
- 手把手实战学习,实践实际相结合
👨🎓试用人群
- 对于 Springboot 相熟然而不晓得正当分层 小白
- 有本人分层思路能够相互分享学习
🎁疾速链接
公众号:JavaDog 程序狗
在公众号,发送【分层】,无任何套路即可取得
或拜访 https://blog.javadog.net/archives/boot-module
🍩水图
下图反面教材,传统单体利用,构造臃肿
下图分层截选自自己的一个小我的项目,模块清晰,分工明确
咱们要实现的小栗子的分层
注释
🥫1.IDEA 新建我的项目
起名第一步,一个好名字, 说不定是个好的开始
如果咱们的我的项目是个 聊天相干 的我的项目,英文对应chat, 所以定义我的项目名为chat-boot,其余的以此效仿
点击 New->project
抉择 Maven 项 目,并抉择 适合 JDK 版本, 点击 Next
录入项目名称,并填写 GAV 坐标,点击 Finish
删除无用文件及目录,如 src 目录和 *.iml 文件
删除后我的项目目录
批改 pom.xml 中依赖,减少 spring-boot-starter-parent
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
</parent>
🌭2. 创立子模块 -dependencies(依赖层)
右击我的项目 chat-boot,new ->Moudle 新建模块 chat-boot-dependencies
抉择对应 Module SDK 版本,自己抉择 jdk1.8
填写子模块名 chat-boot-dependencies,而后查看对应 GAV,点击 Finish
生成子模块 chat-boot-dependencies 如下图
删除 chat-boot-dependencies 下无用文件及目录,如 src 目录,删除无用目录如下
欠缺 chat-boot-dependencies 下 pom.xml 依赖,罕用依赖 放入,作为 依赖主体 ,以下是本狗罕用依赖,可酌情抉择; 记得把 packaging 改为 pom
<?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">
<parent>
<artifactId>chat-boot</artifactId>
<groupId>net.javadog.chat</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>chat-dependencies</artifactId>
<packaging>pom</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<mysql-connector-java.version>8.0.17</mysql-connector-java.version>
<druid.version>1.1.21</druid.version>
<mybatis-plus.version>3.4.1</mybatis-plus.version>
<fastjson.version>1.2.75</fastjson.version>
<hutool.version>5.5.8</hutool.version>
<lombok.versin>1.18.12</lombok.versin>
<easypoi.version>4.2.0</easypoi.version>
<springfox-swagger2.version>2.9.2</springfox-swagger2.version>
<springfox-swagger-ui.version>2.9.2</springfox-swagger-ui.version>
<knife4j.version>2.0.4</knife4j.version>
<weixin.version>4.4.5.B</weixin.version>
<shiro.version>1.3.2</shiro.version>
<jwt.version>3.2.0</jwt.version>
</properties>
<dependencyManagement>
<dependencies>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!-- 数据库驱动, 可依据本人须要自行删减,默认应用 mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!--hutool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.versin}</version>
</dependency>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox-swagger2.version}</version>
</dependency>
<!--swagger-ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-swagger-ui.version}</version>
</dependency>
<!-- swagger 接口文档 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
</dependency>
<!--easypoi 导入导出 -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>${easypoi.version}</version>
</dependency>
<!--WxJava - 微信开发 Java SDK-->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>${weixin.version}</version>
</dependency>
<!-- 整合 Shiro 平安框架 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
<!-- 集成 jwt 实现 token 认证 -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>${jwt.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
🎯重点
此处用的标签是 dependencyManagement,
dependencyManagement 只是申明依赖,并不实现引入 ,因而 子项目须要显示的申明须要用的依赖 。如果 不在子项目中申明依赖,是不会从父我的项目中继承下来 ; 只有在子项目中写了该依赖项,并且没有指定具体版本,才会从父我的项目中继承该项,并且 version 和 scope 都读取自父 pom; 另外如果子项目中指定了版本号,那么会应用子项目中指定的 jar 版本。
🍪3. 创立子模块 -main(主启动层)
右击我的项目 chat-boot,new ->Moudle 新建模块 chat-boot-main
抉择对应 Module SDK 版本,本狗抉择 jdk1.8,点击 Next
填写子模块名 chat-boot-main,而后查看对应 GAV,点击 Finish
生成子模块 chat-boot-main 如下图
欠缺 chat-boot-main 模块下 pom.xml 中依赖
- 引入必要依赖
- 欠缺 profiles 标签中环境相干
- 配置 build 标签中插件
<?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">
<parent>
<artifactId>chat-boot</artifactId>
<groupId>net.javadog.chat</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>chat-boot-main</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>net.javadog.chat</groupId>
<artifactId>chat-boot-dependencies</artifactId>
<version>1.0-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<!--swagger-ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<!-- swagger 接口文档 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
</dependency>
</dependencies>
<build>
<finalName>chat</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/webapp</directory>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
<profiles>
<profile>
<id>local</id>
<properties>
<spring.active>local</spring.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>dev</id>
<properties>
<spring.active>dev</spring.active>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<spring.active>prod</spring.active>
</properties>
</profile>
</profiles>
</project>
🎯重点
- 配置引入依赖 chat-boot-dependencies, 用作此模块依赖引入
<dependencyManagement>
<dependencies>
<dependency>
<groupId>net.javadog.chat</groupId>
<artifactId>chat-boot-dependencies</artifactId>
<version>1.0-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
- 配置 build 标签用于欠缺插件 plugins,其中蕴含 maven-compiler-plugin 和 maven-resources-plugin
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<configuration>
<delimiters>
<delimiter>@</delimiter>
</delimiters>
<useDefaultDelimiters>false</useDefaultDelimiters>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/webapp</directory>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
- 配置 profiles 环境变量标签,用于不便打包切换,本狗设置了 local、dev、prod 三种环境
<profiles>
<profile>
<id>local</id>
<properties>
<spring.active>local</spring.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>dev</id>
<properties>
<spring.active>dev</spring.active>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<spring.active>prod</spring.active>
</properties>
</profile>
</profiles>
操作可在 IDEA 右上角不便切换环境
💥切记肯定被动 Reload 一下 Maven 依赖
💥切记肯定被动 Reload 一下 Maven 依赖
💥切记肯定被动 Reload 一下 Maven 依赖
在 chat-boot-main 模块中退出启动类,在 src/main/java 下右键 New=>Java Class
录入启动类名 ChatApplication
欠缺 ChatApplication 启动类代码
package net.javadog.chat;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author: hdx
* @Date: 2023-01-28 11:24
* @version: 1.0
**/
@SpringBootApplication
@ServletComponentScan
@Slf4j
@EnableSwagger2
@EnableKnife4j
public class ChatApplication {public static void main(String[] args) throws UnknownHostException {
// 启动类
ConfigurableApplicationContext application = SpringApplication.run(ChatApplication.class, args);
// 打印根底信息
info(application);
}
static void info(ConfigurableApplicationContext application) throws UnknownHostException {Environment env = application.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
String active = env.getProperty("spring.profiles.active");
String contextPath = env.getProperty("server.servlet.context-path");
if (contextPath == null) {contextPath = "";}
log.info("\n----------------------------------------------------------\n\t" +
"欢送拜访 \thttps://blog.javadog.net\n\t" +
"示例程序【" + active + "】环境已启动! 地址如下:\n\t" +
"Local: \t\thttp://localhost:" + port + contextPath + "\n\t" +
"External: \thttp://" + ip + ':' + port + contextPath + '\n' +
"Swagger 文档: \thttp://" + ip + ":" + port + contextPath + "/doc.html\n" +
"----------------------------------------------------------");
}
}
配置 application.yml 文件
application.yml
#============================#
# server 配置
#============================#
server:
port: 82
max-http-header-size: 10240
servlet:
context-path: /chat/v1
#============================#
# spring 配置
#============================#
spring:
application:
# 利用名
name: chat
profiles:
active: @spring.active@
servlet:
multipart:
max-request-size: 100MB
max-file-size: 100MB
jackson:
time-zone: GMT+8
date-format: yyyy-MM-dd HH:mm:ss.SSS
locale: zh_CN
serialization:
# 格式化输入
indent_output: false
main:
allow-circular-references: true
#解决 swagger 版本门路不兼容问题
mvc:
pathmatch:
matching-strategy: ant_path_matcher
#============================#
# mybatisplus 配置
#============================#
mybatis-plus:
mapper-locations: classpath:mapper/*.xml
configuration:
map-underscore-to-camel-case: true
cache-enabled: true
lazy-loading-enabled: true
multiple-result-sets-enabled: true
log-impl: org.apache.ibatis.logging.nologging.NoLoggingImpl
global-config:
banner: false
db-config:
id-type: assign_id
table-underline: true
enable-sql-runner: true
#数据库类型
db-type: MYSQL
configuration-properties:
prefix:
#如果数据库为 postgresql,则须要配置为 blobType: BINARY
blobType: BLOB
#如果数据库为 oracle 或 mssql,则须要配置为 boolValue: 1
boolValue: true
#============================#
# logging 配置
#============================#
logging:
level:
root: info
file:
path: /root/javadog/chat/logs/${spring.application.name}/
name: ${spring.application.name}
logback:
rollingpolicy:
max-history: 7
max-file-size: 10MB
#============================#
# file 配置
#============================#
file:
# 动态附件前缀
static-prefix: attach
# 上传的文件对外裸露的拜访门路
access-path-pattern: /${file.static-prefix}/**
# 文件上传目录
upload-folder: /root/javadog/chat/
# 文件上传最大
max-post-size: 10
application-local.yml
# 服务配置
server:
port: 8001
max-http-header-size: 10240
# Mysql 数据库
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/chat-boot?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=CTT&nullCatalogMeansCurrent=true
username: root
password: root
redis:
host: localhost
port: 6379
password:
application-dev.yml
# 服务配置
server:
port: 7001
max-http-header-size: 10240
# mybatisplus 配置
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
application-prod.yml
# 服务配置
server:
port: 8005
🌊顺便加一下 logback-spring.xml 日志文件
<?xml version="1.0" encoding="UTF-8" ?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter"/>
<conversionRule conversionWord="wex"
converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/>
<conversionRule conversionWord="wEx"
converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter"/>
<property name="CONSOLE_LOG_PATTERN"
value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:-}){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<property name="FILE_LOG_PATTERN"
value="${FILE_LOG_PATTERN:-%d{yyyy-MM-dd HH:mm:ss.SSS} ${LOG_LEVEL_PATTERN:-%5p} ${PID:-} --- [%t] %-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<springProperty scope="context" name="application.name" source="spring.application.name" defaultValue="javadog"/>
<springProperty scope="context" name="logging.path" source="logging.file.path" defaultValue="logs"/>
<springProperty scope="context" name="logging.file.max-size" source="logging.logback.rollingpolicy.max-size"
defaultValue="10MB"/>
<springProperty scope="context" name="logging.file.max-history" source="logging.logback.rollingpolicy.max-history"
defaultValue="30"/>
<contextName>${application.name}</contextName>
<springProfile name="dev,prod">
<!-- 输入到控制台 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="console"/>
</root>
</springProfile>
<springProfile name="dev,test,prod">
<!-- 输入到文件 -->
<appender name="file-info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logging.path}/info/${application.name}-info.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logging.path}/info/${application.name}-info.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${logging.file.max-size}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!-- 只保留最近 n 天的日志 -->
<maxHistory>${logging.file.max-history}</maxHistory>
</rollingPolicy>
<!-- 追加形式记录日志 -->
<append>true</append>
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
</encoder>
</appender>
<appender name="file-warn" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>warn</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<file>${logging.path}/warn/${application.name}-warn.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logging.path}$/warn/${application.name}-warn.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${logging.file.max-size}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!-- 只保留最近 n 天的日志 -->
<maxHistory>${logging.file.max-history}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
</encoder>
</appender>
<appender name="file-error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>error</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<file>${logging.path}/error/${application.name}-error.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logging.path}/error/${application.name}-error.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${logging.file.max-size}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!-- 只保留最近 n 天的日志 -->
<maxHistory>${logging.file.max-history}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="file-info"/>
<appender-ref ref="file-warn"/>
<appender-ref ref="file-error"/>
</root>
</springProfile>
</configuration>
启动一下我的项目试试,启动如下证实胜利。如果报错少依赖请再拉一下 Maven 依赖!!!
🍇4. 创立子模块 -module(模块层)
右击我的项目 chat-boot,new ->Moudle 新建模块 chat-boot-module
填写子模块名 chat-boot-module,而后查看对应 GAV,点击 Finish
生成子模块 chat-boot-module 如下图
删除 chat-boot-module 下无用文件及目录,如 src 目录,删除无用目录如下
自此内部大框架初步搭建胜利
欠缺 chat-boot-module 下 pom.xml 依赖,如 lombok,web 等必要依赖
<?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">
<parent>
<artifactId>chat-boot</artifactId>
<groupId>net.javadog.chat</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>chat-boot-module</artifactId>
<packaging>pom</packaging>
<modules>
<module>chat-boot-common</module>
<module>chat-boot-controller</module>
<module>chat-boot-dao</module>
<module>chat-boot-dto</module>
<module>chat-boot-entity</module>
<module>chat-boot-service</module>
</modules>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>net.javadog.chat</groupId>
<artifactId>chat-boot-dependencies</artifactId>
<version>${project.parent.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--WxJava - 微信开发 Java SDK-->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--hutool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<!--swagger-ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<!-- 整合 Knife4j-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
</dependency>
<!-- 整合 Shiro 平安框架 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
</dependency>
<!--jwt-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
</project>
肯定要从新拉取依赖!
肯定要从新拉取依赖!
肯定要从新拉取依赖!
🍉5. 创立 chat-boot-module 模块下对应性能分层
目前本狗分为如下 6 层
- common- 共通层
- controller- 控制器层
- dao- 数据长久层
- dto- 数据传输对象层
- entity- 实体层
- service- 业务逻辑层
顺次依照上述增加模块形式进行新增子模块,本狗如下示例一个,其余都如法炮制
右击我的项目 chat-boot-module,new ->Moudle 新建模块 chat-boot-common
肯定看清楚父模块是否正确
肯定看清楚父模块是否正确
肯定看清楚父模块是否正确
确认父级模块后,点击 Finish,生成 chat-boot-common 模块
顺次依照上述办法,新建其余模块
chat-boot-controller模块
chat-boot-dao模块
chat-boot-dto模块
chat-boot-entity模块
chat-boot-service模块
总体模块雏形根本实现
🍧6. 理论流程填充
- 模仿失常 前端申请 到后盾服务调用过程,进行理论代码补充
在 chat-boot-entity 下新建实体类 User,在 src/main/java 下右键 New=>Java Class,录入包名及类名
package net.javadog.chat.entity;
import lombok.Data;
/**
* @author: hdx
* @Date: 2023-01-28 14:26
* @version: 1.0
**/
@Data
public class User {
private Long id;
private String username;
private String idCard;
}
在 chat-boot-dto 下新建目 request 和 response,别离代表 申请传输对象和返回传输对象,并别离在目录下创立 UserRequest.java 和 UserResponse.java
package net.javadog.chat.request;
import lombok.Data;
/**
* @author: hdx
* @Date: 2023-01-28 14:59
* @version: 1.0
**/
@Data
public class UserRequest {
private Long id;
private String username;
}
package net.javadog.chat.response;
import lombok.Data;
/**
* @author: hdx
* @Date: 2023-01-28 14:59
* @version: 1.0
**/
@Data
public class UserResponse {
private Long id;
private String username;
}
在 chat-boot-dao 下批改 chat-boot-dao 模块下批改 pom.xml 文件依赖,引入 chat-boot-entity; 并增对应 UserMapper.java
package net.javadog.chat.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import net.javadog.chat.entity.User;
/**
* 用户 mapper
*
* @author: hdx
* @Date: 2023-01-10 11:43
* @version: 1.0
**/
public interface UserMapper extends BaseMapper<User> {
}
<?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">
<parent>
<artifactId>chat-boot-module</artifactId>
<groupId>net.javadog.chat</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>chat-boot-dao</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>net.javadog.chat</groupId>
<artifactId>chat-boot-entity</artifactId>
<version>${project.parent.version}</version>
</dependency>
</dependencies>
</project>
在 chat-boot-service 下新建目录 service 和 impl,并在对应目录下新建 UserService.java 和 UserServiceImpl.java,并批改 chat-boot-service 模块下批改 pom.xml 文件依赖,引入 chat-boot-dto,chat-boot-dao
package net.javadog.chat.service;
import com.baomidou.mybatisplus.extension.service.IService;
import net.javadog.chat.entity.User;
/**
* 用户接口
*
* @author: hdx
* @Date: 2023-01-10 11:53
* @version: 1.0
**/
public interface UserService extends IService<User> {
}
package net.javadog.chat.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.javadog.chat.entity.User;
import net.javadog.chat.mapper.UserMapper;
import net.javadog.chat.service.UserService;
import org.springframework.stereotype.Service;
/**
* 用户接口实现类
*
* @author: hdx
* @Date: 2023-01-10 11:55
* @version: 1.0
**/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {}
<?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">
<parent>
<artifactId>chat-boot-module</artifactId>
<groupId>net.javadog.chat</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>chat-boot-service</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>net.javadog.chat</groupId>
<artifactId>chat-boot-dao</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>net.javadog.chat</groupId>
<artifactId>chat-boot-dto</artifactId>
<version>${project.parent.version}</version>
</dependency>
</dependencies>
</project>
在 chat-boot-controller 创立 UserController.java, 并批改 chat-boot-controller 模块下批改 pom.xml 文件依赖,引入 chat-boot-dto,chat-boot-service
package net.javadog.chat.controller;
import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.javadog.chat.entity.User;
import net.javadog.chat.request.UserRequest;
import net.javadog.chat.response.UserResponse;
import net.javadog.chat.service.UserService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* 用户控制器
*
* @author: hdx
* @Date: 2022-12-07 15:48
* @version: 1.0
**/
@Api(tags = "用户控制器")
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@ApiOperation(value = "用户详情", notes = "用户详情")
@GetMapping
public UserResponse detail(UserRequest userRequest){UserResponse userResponse = new UserResponse();
User user = userService.getById(userRequest.getId());
BeanUtil.copyProperties(user, userResponse);
return userResponse;
}
}
🎯重要补充
1. 切记批改 chat-boot-main 下的 pom.xml 依赖,将 chat-boot-controller 模块退出
2. 切记批改 chat-boot-main 下的 pom.xml 依赖,将 chat-boot-dao 模块退出
3. 切记批改启动类 ChatApplication 中退出 @MapperScan 注解
<?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">
<parent>
<artifactId>chat-boot</artifactId>
<groupId>net.javadog.chat</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>chat-boot-main</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>net.javadog.chat</groupId>
<artifactId>chat-boot-dependencies</artifactId>
<version>1.0-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<!--swagger-ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<!-- swagger 接口文档 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
</dependency>
<!-- controller -->
<dependency>
<groupId>net.javadog.chat</groupId>
<artifactId>chat-boot-controller</artifactId>
<version>${project.parent.version}</version>
</dependency>
<!-- dao -->
<dependency>
<groupId>net.javadog.chat</groupId>
<artifactId>chat-boot-dao</artifactId>
<version>${project.parent.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<configuration>
<delimiters>
<delimiter>@</delimiter>
</delimiters>
<useDefaultDelimiters>false</useDefaultDelimiters>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/webapp</directory>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
<profiles>
<profile>
<id>local</id>
<properties>
<spring.active>local</spring.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>dev</id>
<properties>
<spring.active>dev</spring.active>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<spring.active>prod</spring.active>
</properties>
</profile>
</profiles>
</project>
package net.javadog.chat;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author: hdx
* @Date: 2023-01-28 11:24
* @version: 1.0
**/
@SpringBootApplication
@ServletComponentScan
@Slf4j
@EnableSwagger2
@EnableKnife4j
@MapperScan(basePackages = {"net.javadog.chat.mapper"})
public class ChatApplication {public static void main(String[] args) throws UnknownHostException {
// 启动类
ConfigurableApplicationContext application = SpringApplication.run(ChatApplication.class, args);
// 打印根底信息
info(application);
}
static void info(ConfigurableApplicationContext application) throws UnknownHostException {Environment env = application.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
String active = env.getProperty("spring.profiles.active");
String contextPath = env.getProperty("server.servlet.context-path");
if (contextPath == null) {contextPath = "";}
log.info("\n----------------------------------------------------------\n\t" +
"欢送拜访 \thttps://blog.javadog.net\n\t" +
"示例程序【" + active + "】环境已启动! 地址如下:\n\t" +
"Local: \t\thttp://localhost:" + port + contextPath + "\n\t" +
"External: \thttp://" + ip + ':' + port + contextPath + '\n' +
"Swagger 文档: \thttp://" + ip + ":" + port + contextPath + "/doc.html\n" +
"----------------------------------------------------------");
}
}
🦔7. 示例 DB 更新
- 模仿失常 前端申请 到后盾服务调用过程,进行理论代码补充
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (`id` bigint(20) NOT NULL COMMENT 'id',
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户名',
`id_card` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '身份证',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'JavaDog', '123123');
🧩8. 拜访测试
浏览器拜访 http://localhost:8001/chat/v1/user?id=1
测试胜利如下图所示
总结
以上示例只是简略示范分层思路,其中代码逻辑实现形式有很多种,大家选取实用本人就好,心愿本人的思路能对大家有帮忙
如遇短少依赖状况,肯定要从新拉取依赖!
写在最初
此生两悔,悔遇见你,更悔未早遇见你,珍惜当下领有,勿念今日美妙。