SpringBoot 多模块构建

1,554 阅读5分钟

最近看了些SpringBoot的知识,学会了创建SpringBoot项目、开发RESRful接口、使用模板引擎、Swagger2构建API文档、Spring Security、Mybatis、RabbitMQ、Redis集成等等。但是在github上看了一个前后端分离的项目后,完全傻眼了,这么多工程为什么启动一个就能运行呢?为什么执行了mvn install和mvn package就可以运行了呢?于是有了这篇文章,基础弱,懂得少,就得一点点的搜索再补充自己的知识,本文参考了其他大神的文章,但只做自己的学习记录。

本文使用的开发工具及技术版本

  • IDEA
  • JDK8
  • MAVEN3.6.0
  • SpringBoot2.X

子module的规划及依赖关系:

  • entity:实体类所在工程
  • web:controller所在工程,依赖entity、service、mapper
  • service:service类所在工程,依赖entity、mapper
  • mapper:mybatis所在工程,负责和数据库的交互,依赖entity

创建父工程

  1. 用IDEA快速创建一个MAVEN工程,删除无用的文件src文件夹,只保留pom.xml即可
  2. 在pom文件中补充项目的基本信息
    <!-- 基本信息 -->
    <description>SpringBoot 多模块构建</description>
    <modelVersion>4.0.0</modelVersion>
    <name>springboot-modules-demo</name>
    <packaging>pom</packaging>

需要特别注意的是,打包方式父类中应该指定为pom,而子类中应指定为jar或war,下边创建子工程时再次提醒此处。

  1. 继承SpringBoot提供的父工程
<!-- 继承SpringBoot提供的父工程 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/>
    </parent>
  1. 按照项目的规划,在pom文件中声明父工程包含的子模块
    <!-- 模块说明:这里声明多个子模块 -->
    <modules>
        <module>entity</module>
        <module>web</module>
        <module>service</module>
        <module>mapper</module>
    </modules>

创建子工程

创建entity工程

  1. 在父工程上选择右键->New->Module...->创建Maven工程
  2. 创建完成后,我们打开pom.xml可以观察到如下代码
    <parent>
        <artifactId>springboot-modules-demo</artifactId>
        <groupId>com.dongfeng</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

父工程已经引用为我们创建的父工程

  1. 引入entity所需的依赖
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
    </dependencies>
  1. 创建User实体类
package com.dongfeng.user;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.hibernate.validator.constraints.Length;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import java.util.Date;

/**  
 * 描述: <br>
 * @date 2019/4/27 13:15
 * @author zhangzhd
 **/
@Entity
@Data
@NoArgsConstructor
public class User {
	@Id
	@GeneratedValue
	private Long id;

	@NotEmpty(message = "姓名不能为空")
	@Column(nullable = false, unique = true)
	private String username;

	@Max(value = 100, message = "年龄不能大于 100 岁")
	@Min(value = 18, message = "必须年满 18 岁!")
	private int age;

	@NotEmpty(message = "密码不能为空")
	@Length(min = 6, message = "密码长度不能小于 6 位")
	private String password;

	@Column(nullable = false)
	private String regTime;

	@CreationTimestamp
	private Date createTime;

	@UpdateTimestamp
	private Date updateTime;

	public User(@NotEmpty(message = "姓名不能为空") String userName,
			@Max(value = 100, message = "年龄不能大于 100 岁") @Min(value = 18, message = "必须年满 18 岁!") int age,
			@NotEmpty(message = "密码不能为空") @Length(min = 6, message = "密码长度不能小于 6 位") String passWord, String regTime) {
		this.username = userName;
		this.age = age;
		this.password = passWord;
		this.regTime = regTime;
	}
}

创建mapper工程

  1. 因为controller依赖service,service依赖mapper工程,所以我们先来创建mapper工程
  2. 与上述创建工程类似的步骤,再次创建mapper工程
  3. 在pom文件中引入所需的依赖
<!-- mapper模块相关依赖 -->
    <dependencies>
        <dependency>
            <groupId>com.dongfeng</groupId>
            <artifactId>entity</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!--此处我们直接引用baomidou来代替mybatis-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>
    </dependencies>
  1. 创建访问数据接口类
package com.dongfeng.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.dongfeng.user.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;

@Mapper
public interface UserMapper extends BaseMapper<User> {
	List<User> getAll();
}
  1. 创建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.runner.mapper.UserMapper">
    <select id="getAll" resultType="com.runner.model.User">
        SELECT username AS "username",password as "password",age,reg_time as "regTime",id FROM user
    </select>
</mapper>
  1. 创建访问数据连接、mybatisplus的配置文件 在resources目录下新增application.properties文件,文件内容如下:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/marathon?serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=root

mybatis-plus.mapper-locations: classpath*:/mapper/**/*.xml
  1. 注意:创建启动类后应该配置扫描的mapper包路径(本文计划将启动类创建在web工程中)

创建service工程

  1. 与上述创建工程类似的步骤,再次创建service工程
  2. 在pom文件中引入所需的依赖
    <dependencies>
        <dependency>
            <groupId>com.dongfeng</groupId>
            <artifactId>entity</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.dongfeng</groupId>
            <artifactId>mapper</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
  1. 创建service接口类及实现类 接口类
package com.dongfeng.service;

import com.dongfeng.user.User;

import java.util.List;

public interface UserService {
	List<User> getAll();
}

实现类

package com.dongfeng.service.impl;

import com.dongfeng.mapper.UserMapper;
import com.dongfeng.service.UserService;
import com.dongfeng.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Override
	public List<User> getAll() {
		return userMapper.getAll();
	}
}

创建web工程

  1. 与上述创建工程类似的步骤,再次创建web工程
  2. 在pom文件中引入所需的依赖
<!-- Web模块相关依赖 -->
    <dependencies>
        <dependency>
            <groupId>com.dongfeng</groupId>
            <artifactId>entity</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.dongfeng</groupId>
            <artifactId>service</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

注意需要引入entity和service的依赖。

  1. 创建Controller类
package com.dongfeng.user;

import com.dongfeng.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@RequestMapping(value="/users")
public class UserRestfulController {

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/getUserList", method = RequestMethod.GET)
	public List<User> getUserList() {
		List<User> users = userService.getAll();
		return users;
	}
}

  1. 创建项目的启动类
package com.dongfeng;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
@MapperScan("com.dongfeng.mapper")
public class WebApplication extends SpringBootServletInitializer {
	public static void main(String[] args) {
		SpringApplication.run(WebApplication.class, args);
	}
}

接下来就可以启动刚才编写的WebApplication类来查看效果了,启动后访问http://127.0.0.1:8080/users/getUserList,可以在浏览器看到返回的数据结果,大功告成。