Spring Boot|多模块

简单搭了一套多模块的框架,将controller、service、dao等分成不同的模块,可以相互协作又层级间相互解耦。

一、环境搭建

先基于maven创建一个父级框架multimodule

 src文件夹可以删除

在父级multimodule中的pom.xml文件中加入如下内容,这样子类就不需要再重复引用了。

 

   multimodule上右键新增一个Module,这次我们创建一个spring boot项目,common模块。

 

 

修改common层的pom.xml文件

   使用同样的方法创建一个dao、service、web层,创建好的结构如下:

层级架构:dao > service > web,common层同时为service、web层提供服务,修改层级间的引用关系,如下:

multimodule层:

web层:

service层:

注意下面的内容必须写在需要打包的模块里,不需要打包的模块要去掉。比如当前项目只需要出现在web模块的pom里,否则最终打包会报找不到引用模块的错误。

  

至此,基础环境搭建完毕

 二、测试打包

创建一个简单示例,演示运行流程。

common

/**
 * 测试工具类
 *
 * @author jyy
 * @since 2020/12/4 16:03
 */public class DemoUtils {

    public static void print(String s) {
        System.out.println(s);
    }
}

dao

/**
 * 数据库交互层
 *
 * @author jyy
 * @since 2020/12/4 16:25
 */
@Repository
public class DemoDao {

    public void test() {
        System.out.print("hello dao");
    }
}

service

/**
 * 逻辑层
 * @author jyy
 * @since 2020/12/4 16:27
 */
@Service
public class DemoService {

    @Resource
    private DemoDao demoDao;

    public void test() {
        DemoUtils.print("hello service");
        demoDao.test();
    }
}

web

/**
 * 视图层
 *
 * @author jyy
 * @since 2020/12/4 16:29
 */
@RestController
public class DemoController {

    @Resource
    private DemoService demoService;

    @GetMapping("test")
    public void test() {
        DemoUtils.print("hello controller");
        demoService.test();
    }
}

运行web层,调用test方法,执行结果如下:

  整个项目,可以每层分别打包,也可以整体打包, 在multimodule层打包,涉及到的各个模块都会重新打包一遍。

原文地址:https://www.cnblogs.com/maikucha/p/14086107.html