Gradle 整合 SpringBoot
欢迎来到我的 ChatGPT 中转站,极具性价比,为付费不方便的朋友提供便利,有需求的可以添加左侧 QQ 二维码,另外,邀请新用户能获取余额哦!最后说一句,那啥:请自觉遵守《生成式人工智能服务管理暂行办法》。
# 创建 Springboot 项目
Spring Boot Gradle 插件在 Gradle 提供 Spring Boot 支持。它允许您打包可执行 jar 或 war 归档文件,运行 SpringBoot 应用程序,并使用 Spring-Boot-dependencies 提供的依赖管理。相关文档请参考:Spring Boot Gradle Plugin Reference Guide (opens new window)。
# 引入 springboot 插件
该插件发布在 Gradle 的插件门户网站上,可以使用插件块来应用
plugins {
id 'org.springframework.boot' version '2.3.7.RELEASE' //维护springboot版本号,不单独使用,和下面两个插件一起用
id 'io.spring.dependency-management' version '1.0.10.RELEASE'
//进行依赖管理,在引入其它boot依赖时省略版本号、 解决jar包冲突问题
id 'java'
}
1
2
3
4
5
6
2
3
4
5
6
# 引入所需要的依赖
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-web' //省略版本,原生bom支持,插件management提供
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 执行 gradle bootRun 指令
- 要想运行当前 Springboot 项目,直接执行 gradle bootRun 指令或者 idea 右侧按钮即可。
- 当然如果想让当前项目打成可执行 jar 包,只需执行: gradle bootJar 指令即可。
- Cloud 项目创建也可以借助于脚手架创建,与 Boot 项目类似。
# 拓展 spring-boot-gradle-plugin 插件
buildscript {
repositories {
maven { url 'https://maven.aliyun.com/repository/public' }
}
dependencies {
classpath 'org.springframework.boot:spring-boot-gradle-plugin:2.4.1'
}
}
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 基于 SSM 多模块项目案例
# 多项目模块划分
meinian-mobile-web: 美年旅游项目的用户系统
meinian-web: 美年旅游项目的管理员系统
meinian-service: 美年旅游项目的业务逻辑层
meinian-dao: 美年旅游项目的持久化层
meinian-bean: 美年旅游项目的 Model 封装
# 项目搭建前配置分析
# 项目配置
# settings.gradle 文件
rootProject.name = 'meinian-parent'
include 'meinian-web'
include 'meinian-mobile-web'
include 'meinian-service'
include 'meinian-dao'
include 'meinian-bean'
1
2
3
4
5
6
2
3
4
5
6
# 根 build.gradle 文件
plugins {
id 'java'
}
group 'com.meinian'
version '1.0-SNAPSHOT'
subprojects {
//添加插件
apply plugin: 'java'
//基本JDK配置
sourceCompatibility = 1.8
targetCompatibility = 1.8
compileJava.options.encoding "UTF-8"
compileTestJava.options.encoding "UTF-8"
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
group 'com.meinian'
version '1.0-SNAPSHOT'
repositories {
mavenLocal()
maven { url "https://maven.aliyun.com/repository/public" }
maven { url "https://maven.aliyun.com/repository/central" }
maven { url "https://maven.aliyun.com/repository/google" }
maven { url "https://maven.aliyun.com/repository/spring" }
mavenCentral()
}
//依赖的配置:设置通用的依赖
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
implementation 'log4j:log4j:1.2.17'
}
test {
useJUnitPlatform()
}
}
project("meinian-bean") {
dependencies {
compileOnly 'org.projectlombok:lombok:1.18.24'
}
}
project("meinian-dao") {
apply plugin: 'java-library'//支持api
dependencies {
api project(':meinian-bean')
implementation 'org.mybatis:mybatis-spring:1.2.3'
implementation 'com.alibaba:druid:1.0.15'
implementation 'org.mybatis:mybatis:3.3.0'
implementation 'mysql:mysql-connector-java:8.0.29'
}
}
project("meinian-service") {
apply plugin: 'java-library'//支持api
dependencies {
api project(':meinian-dao')
implementation 'org.springframework:spring-web:4.1.7.RELEASE'
implementation 'org.springframework:spring-test:4.0.5.RELEASE'
implementation 'org.springframework:spring-jdbc:4.1.7.RELEASE'
implementation 'org.aspectj:aspectjweaver:1.8.6'
}
}
project("meinian-web") {
apply plugin: 'war'
dependencies {
implementation project(':meinian-service')
implementation 'org.springframework:spring-webmvc:4.1.7.RELEASE'
implementation "com.fasterxml.jackson.core:jackson-databind:2.2.3"
implementation "com.fasterxml.jackson.core:jackson-annotations:2.2.3"
implementation "com.fasterxml.jackson.core:jackson-core:2.2.3"
compileOnly 'javax.servlet:servlet-api:2.5'
implementation 'jstl:jstl:1.2'
}
}
project("meinian-mobile-web") {
apply plugin: 'war'
dependencies {
//implementation project(':meinian-bean')
implementation project(':meinian-service')
implementation 'org.springframework:spring-webmvc:4.1.7.RELEASE'
implementation "com.fasterxml.jackson.core:jackson-databind:2.2.3"
implementation "com.fasterxml.jackson.core:jackson-annotations:2.2.3"
implementation "com.fasterxml.jackson.core:jackson-core:2.2.3"
compileOnly 'javax.servlet:servlet-api:2.5'
implementation 'jstl:jstl:1.2'
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# 其他子目录的 build.gradle 文件
删除全部内容即可(空白)。
# 代码演示
# bean
在 meinian-bean 中创建 Admin
package com.meinian.bean;
import java.io.Serializable;
public class Admin implements Serializable {
private Integer id;
private String username;
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Admin{" + "id=" + id + ", username='" + username + '\'' + ", email='" + email + '\'' + '}';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# dao
在 meinian-dao 中创建 AdminMapper
package com.meinian.mapper;
import com.meinian.bean.Admin;
import java.util.List;
public interface AdminMapper {
public List<Admin> getAdminList();
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
<?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.meinian.mapper.AdminMapper">
<select id="getAdminList" resultType="com.meinian.bean.Admin">
select id, username, email
from admin
</select>
</mapper>
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
## jdbc.properties
jdbc.jdbcUrl=jdbc:mysql://192.168.25.10:3306/gradle?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.userName=root
jdbc.password=111111
1
2
3
4
5
2
3
4
5
<!-- mybatis-config.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
1
2
3
4
5
6
7
2
3
4
5
6
7
# service
在 meinian-service 中创建 AdminService
package com.meinian.service;
import com.meinian.bean.Admin;
import com.meinian.mapper.AdminMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class AdminService {
@Autowired
private AdminMapper adminMapper;
@Transactional
public List<Admin> getAdminList() {
return adminMapper.getAdminList();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- applicationContext.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 1.加载properties文件 -->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!-- 2.配置数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="username" value="${jdbc.userName}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="url" value="${jdbc.jdbcUrl}"></property>
<property name="driverClassName" value="${jdbc.driverClass}"></property>
</bean>
<!-- 0.配置扫描包 -->
<context:component-scan base-package="com.meinian">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
<!-- 4.配置数据源事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
<!-- 1.配置spring整合mybatis -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
<!-- 2.配置扫描mapper接口的bean对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.meinian.mapper"/>
</bean>
</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# web
在 meinian-web 中创建 AdminController
package com.meinian.controller;
import com.meinian.bean.Admin;
import com.meinian.service.AdminService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.List;
@Controller
@RequestMapping("/admin")
public class AdminController {
@Qualifier
@Resource
private AdminService adminService;
@RequestMapping("/list")
@ResponseBody
public List<Admin> getAdminList() {
System.out.println("进来了");
List<Admin> adminList = adminService.getAdminList();
System.out.println("出去了");
return adminList;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!-- springmvc.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 1.配置扫描包 -->
<context:component-scan base-package="com.meinian" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
<!-- 2.配置内部资源视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--3.处理静态资源文件 -->
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!--webapp/WEB-INF/web.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<!-- 指定spring 配置文件的路径和名称 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 指定spring的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 2.配置springmvc的前端控制器 -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 2.处理POST请求乱码的过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 3.配置将POST请求转换为PUT或者DELETE请求的过滤器 -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# 微服务实战
# 创建数据库及表
CREATE DATABASE micro_user;
use micro_user;
CREATE TABLE `user` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(30) NOT NULL COMMENT '用户名',
`email` varchar(30) NOT NULL COMMENT '邮箱',
`gender` tinyint DEFAULT '0' COMMENT '性别',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE DATABASE micro_order;
use micro_order;
CREATE TABLE `orderinfo` (
`oid` int unsigned NOT NULL AUTO_INCREMENT,
`uid` int DEFAULT NULL COMMENT '用户id',
`product_name` varchar(30) NOT NULL COMMENT '省份',
PRIMARY KEY (`oid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 搭建项目架构
microservice-parent | 统一管理所有模块的 jar 包版本信息 |
---|---|
microservice-bean | 统一管理所有模块的用到的 pojo 类 |
microservice-common | 统一管理所有模块的用到的工具类、枚举类、异常处理、日志文件、统一返回结果信息 |
microservice-service | 统一封装所有的微服务 |
microservice-gateway | 封装网关信息 |
# microservice-parent
build.gradle
//构建Gradle脚本自身需要的资源,可以声明的资源包括依赖项、第三方插件、maven仓库地址等。
buildscript {
ext {
springBootVersion = '2.2.1.RELEASE'
springCloudVersion = 'Hoxton.RELEASE'
springCloudAlibabaVersion = '0.2.2.RELEASE'
}
//设置仓库
repositories {
maven { url 'https://maven.aliyun.com/nexus/content/groups/public/' }
maven { url 'https://repo.spring.io/milestone' }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
//配置全局, 包括root项目和子项目
allprojects {
group 'com.microservice'
version '1.0-SNAPSHOT'
//配置编码格式
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
//设置仓库
repositories {
maven { url 'https://maven.aliyun.com/nexus/content/groups/public/' }
maven { url 'https://repo.spring.io/milestone' }
}
}
apply from: 'version.gradle'
//配置所有子项目
subprojects {
apply plugin: 'java'
apply plugin: 'java-library' //api
apply plugin: 'io.spring.dependency-management'
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
//公用的依赖
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}
test {
useJUnitPlatform()
}
// dependencyManagement版本统一管理,类似于父maven的dependencyManagement
dependencyManagement {
dependencies {
for (depJar in rootProject.ext.dependencies) {
dependency depJar.value
}
}
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
mavenBom "org.springframework.cloud:spring-cloud-alibaba-dependencies:${springCloudAlibabaVersion}"
}
}
}
project(':microservice-bean') {
description("微服务实战之bean层:存放表对应的实体类")
}
project(":microservice-common") {
description("微服务实战之公共模块:存放微服务常用的工具类")
//依赖
dependencies {
api 'com.alibaba:fastjson'
api 'mysql:mysql-connector-java'
api 'com.baomidou:mybatis-plus-boot-starter'
api 'io.springfox:springfox-swagger2'
api 'io.springfox:springfox-swagger-ui'
api 'io.jsonwebtoken:jjwt'
api 'org.springframework.cloud:spring-cloud-starter-openfeign'
api 'org.springframework.cloud:spring-cloud-starter-alibaba-sentinel'
api 'org.springframework.cloud:spring-cloud-starter-alibaba-nacos-discovery'
}
}
project(":microservice-service") {
description("微服务实战之服务模块:存放各个微服务模块")
apply plugin: 'org.springframework.boot'
subprojects {
apply plugin: 'java-library'
apply plugin: 'org.springframework.boot'
dependencies {
api 'org.springframework.boot:spring-boot-starter-web'
api project(':microservice-bean')
api project(':microservice-common')
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
settings.gradle
rootProject.name = 'microservice-parent'
include 'microservice-bean'
include 'microservice-common'
include 'microservice-service'
include 'microservice-gateway'
include 'microservice-service:service-order'
findProject(':microservice-service:service-order')?.name = 'service-order'
include 'microservice-service:service-user'
findProject(':microservice-service:service-user')?.name = 'service-user'
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
version.gradle
// 依赖版本管理
ext {
version = [
"fastjsonVersion": "1.2.72",
"mybatisPlus" : "3.0.5",
"mysql" : "8.0.28",
"swaggerVersion" : "2.7.0",
"jjwtVersion" : "0.7.0"
]
dependencies = [
"fastjson" : "com.alibaba:fastjson:${version.fastjsonVersion}",
"mybatis-plus-boot-starter": "com.baomidou:mybatis-plus-boot-starter:${version.mybatisPlus}",
"mysql" : "mysql:mysql-connector-java:${version.mysql}",
"swagger" : "io.springfox:springfox-swagger2:${version.swaggerVersion}",
"swaggerUI" : "io.springfox:springfox-swagger-ui:${version.swaggerVersion}",
"jjwt" : "io.jsonwebtoken:jjwt:${version.jjwtVersion}"
]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# microservice-bean
package com.microservice.bean;
public class OrderInfo {
private Integer oid;
private Integer uid;
private String productName;
public Integer getOid() {
return oid;
}
public void setOid(Integer oid) {
this.oid = oid;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
@Override
public String toString() {
return "OrderInfo{" +
"oid=" + oid +
", uid=" + uid +
", productName='" + productName + '\'' +
'}';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.microservice.bean;
public class User {
private Integer id;
private String username;
private String email;
private boolean gender;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", email='" + email + '\'' +
", gender=" + gender +
'}';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# microservice-common
package com.microservice.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class PageConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.microservice.config;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootConfiguration
@EnableSwagger2 //开启Swagger支持
public class SwaggerConfig {
@Bean
public Docket getAdminDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("admin")
.apiInfo(getAdminApiInfo())
.select()
.build();
}
public ApiInfo getAdminApiInfo() {
return new ApiInfoBuilder()
.title("SpringCloud微服务实战")
.description("Gradle构建微服务实战")
.version("1.0")
.contact(new Contact("DFD","https://cn.pornhub.com","dfd@163.com"))
.build();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.microservice.exception;
public class YyghException extends RuntimeException {
private Integer code;
private String message;
public YyghException(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.microservice.handler;
import com.microservice.exception.YyghException;
import com.microservice.result.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.sql.SQLException;
@RestControllerAdvice //凡是由@ControllerAdvice 标记的类都表示全局异常处理类
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)//粒度:
public R handleException(Exception ex) {
ex.printStackTrace();//输出异常:日志文件
return R.error().message(ex.getMessage());
}
@ExceptionHandler(value = RuntimeException.class)//细粒度的异常处理
public R handleRuntimeException(RuntimeException ex) {
ex.printStackTrace();//输出异常:日志文件
return R.error().message("编译时异常");
}
@ExceptionHandler(value = SQLException.class)//细粒度的异常处理
public R handleSqlExcepiton(SQLException ex) {
ex.printStackTrace();//输出异常:日志文件
return R.error().message("Sql异常");
}
@ExceptionHandler(value = ArithmeticException.class)//细粒度的异常处理
public R handleArithmeticException(ArithmeticException ex) {
ex.printStackTrace();//输出异常:日志文件
return R.error().message("数学异常");
}
@ExceptionHandler(value = YyghException.class)//细粒度的异常处理
public R handleYyghException(YyghException ex) {
ex.printStackTrace();//输出异常:日志文件
return R.error().message(ex.getMessage()).code(ex.getCode());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.microservice.result;
import java.util.HashMap;
import java.util.Map;
public class R {
private Integer code;
private Boolean success;
private String message;
private Map<String, Object> data = new HashMap<String, Object>();
private R() {
}
public static R ok() {
R r = new R();
r.code = REnum.SUCCESS.getCode(); //硬编码:枚举类:代码规范的
r.success = REnum.SUCCESS.getFlag();
r.message = REnum.SUCCESS.getMessage();
return r;
}
public static R error() {
R r = new R();
r.code = REnum.ERROR.getCode();
r.success = REnum.ERROR.getFlag();
r.message = REnum.ERROR.getMessage();
return r;
}
public R code(Integer code) {
this.code = code;
return this;
}
public R success(Boolean success) {
this.success = success;
return this;
}
public R message(String message) {
this.message = message;
return this;
}
public R data(String key, Object value) {
this.data.put(key, value);
return this;
}
public R data(Map<String, Object> map) {
this.data = map;
return this;
}
public Integer getCode() {
return code;
}
public Boolean getSuccess() {
return success;
}
public String getMessage() {
return message;
}
public Map<String, Object> getData() {
return data;
}
@Override
public String toString() {
return super.toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.microservice.result;
public enum REnum {
SUCCESS(20000, "成功", true),
ERROR(20001, "失败", false);
//枚举项:
private Integer code;
private String message;
private Boolean flag;
REnum(Integer code, String message, Boolean flag) {
this.code = code;
this.message = message;
this.flag = flag;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# microservice-service
# service-order
package com.microservice.order.controller;
import com.microservice.bean.OrderInfo;
import com.microservice.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderService orderService;
@GetMapping("/info/{id}")
public List<OrderInfo> getOrderList(@PathVariable("id") Integer id) {
return orderService.getUserInfo(id);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.microservice.order.mapper;
import com.microservice.bean.OrderInfo;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface OrderMapper {
@Select("select oid,uid,product_name productName from orderinfo where uid = #{uid}")
public List<OrderInfo> getOrderList(Integer uid);
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
package com.microservice.order.service;
import com.microservice.bean.OrderInfo;
import com.microservice.order.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
@Transactional(readOnly = true)
public List<OrderInfo> getUserInfo(Integer uid) {
return orderMapper.getOrderList(uid);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.microservice.order;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan("com.microservice")
@MapperScan("com.microservice.order.mapper")
@EnableDiscoveryClient
public class OrderMainStarterApp {
public static void main(String[] args) {
try {
SpringApplication.run(OrderMainStarterApp.class, args);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
server:
profiles:
active: dev
port: 7778
spring:
application:
name: service-order
datasource:
username: root
password: 111111
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.25.10:3306/micro_order?serverTimezone=Asia/Shanghai&useSSL=false
cloud:
nacos:
discovery:
server-addr: 192.168.25.10:8848
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# service-user
package com.microservice.user.controller;
import com.microservice.result.R;
import com.microservice.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/info/{id}")
public R getUserInfo(@PathVariable Integer id) {
Map<String, Object> userInfo = userService.getUserInfo(id);
return R.ok().data(userInfo);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.microservice.user.feign;
import com.microservice.bean.OrderInfo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
@FeignClient(value = "service-order")
public interface OrderFeignClient {
@GetMapping("/order/info/{id}")
public List<OrderInfo> getOrderList(@PathVariable("id") Integer id);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.microservice.user.mapper;
import com.microservice.bean.User;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
@Select("select id,username,email,gender from user where id = #{id}")
public User getUserInfo(Integer id);
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
package com.microservice.user.service;
import com.microservice.user.feign.OrderFeignClient;
import com.microservice.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.Map;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private OrderFeignClient orderFeignClient;
@Transactional(readOnly = true)
public Map<String, Object> getUserInfo(Integer id) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("user", userMapper.getUserInfo(id));
map.put("orderList", orderFeignClient.getOrderList(id));
return map;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
server:
profiles:
active: dev
port: 7777
spring:
datasource:
username: root
password: 111111
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.25.10:3306/micro_user?serverTimezone=Asia/Shanghai&useSSL=false
cloud:
nacos:
discovery:
server-addr: 192.168.25.10:8848
application:
name: service-user
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# microservice-gateway
package com.microservice.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayMainStarterApp {
public static void main(String[] args) {
try {
SpringApplication.run(GatewayMainStarterApp.class, args);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
spring:
cloud:
## 服务注册
nacos:
discovery:
server-addr: 192.168.25.10:8848
gateway:
## 路由
routes:
- id: service-user
uri: lb://service-user
predicates:
- Path=/api/**
filters:
- RewritePath=/api/(?<segment>/?.*), /$\{segment}
- id: service-order
uri: lb://service-order
predicates:
- Path=/api/**
filters:
- RewritePath=/api/(?<segment>/?.*), /$\{segment}
## 跨域
globalcors:
add-to-simple-url-handler-mapping: true ## 解决options请求被拦截问题
cors-configurations:
'[/**]':
allowedOrigins: "*" ## 允许哪些网站的跨域请求
allowedMethods: ## 允许的跨域ajax的请求方式
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" ## 允许在请求中携带的头信息
allowCredentials: true ## 是否允许携带cookie
maxAge: 3600 ## 这次跨域检测的有效期
application:
name: service-gateway
server:
profiles:
active: dev
port: 8888
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
上次更新: 2025/04/12, 07:54:33