【问题标题】:Creating reusable modules with spring boot使用 Spring Boot 创建可重用模块
【发布时间】:2019-04-21 10:46:24
【问题描述】:

我是 Spring 和 Spring boot 的新手,正在寻找是否可以使用 Spring boot 创建可重用的模块。例如,是否可以在 Spring boot 中创建一个项目,比如 UserModule,它处理所有与用户相关的细节,如注册、身份验证,然后创建其他项目,比如 App1 和 App2,它们可以使用 UserModule 作为依赖项?这个想法是避免在每次创建新项目时重新定义与用户相关的实体、服务和控制器。到目前为止,我只找到了Multi Module Project,但我不确定如何使用它来创建可重用的模块。多模块项目只为每个模块创建单独的 pom 文件,但我不确定是否以及如何在新项目中重用。

【问题讨论】:

  • 在另一个 pom 中使用 pom 作为依赖项
  • 你只需要添加到你的 pom 作为依赖项。
  • 为什么需要 Spring Boot?你已经可以用纯 Java 做到这一点了。
  • 我尝试将一个应用程序打包为 jar 并将该 jar 用作第二个项目中的依赖项(不使用多模块),但我无法从第二个项目调用第一个项目中的服务。我做错了吗?

标签: java spring spring-boot reusability


【解决方案1】:

Spring 支持多模块项目。唯一需要的约定是在 pom.xml 中声明模块和父项目。通过示例 pom.xml here,Spring 门户有非常好的文档和相同的示例。

<?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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>gs-multi-module</artifactId>
    <version>0.1.0</version>
    <packaging>pom</packaging>

    <modules>
        <module>library</module>
        <module>application</module>
    </modules>

</project> 

【讨论】:

  • 这不要求库和应用程序目录位于具有父 pom 文件的父目录中吗?我正在寻找的是应用程序2,它位于父目录之外的单独目录中,能够使用库。这可能吗?
  • 如果您使用模块/项目作为依赖项,这是可能的
  • 我尝试创建一个名为 notification 的新项目,它只有一个具有单一方法的 NotificationService。我做了mvn package 为这个项目创建了一个jar 文件,然后mvn install:install-file 使jar 现在可以在我的.m2 目录中使用。接下来,我在一个单独的目录中创建了另一个名为 tasks 的项目,并在其 pom.xml 中添加了 notification jar 作为依赖项。然后从 TaskController,我尝试访问 NotificationService,但我无法做到这一点。我做错什么了吗?
  • tasks的pom.xml文件中,我有com.testmodulenotification 0.0.1-SNAPSHOT 现在,在 TaskController 中,当我尝试 import com.testmodule.notification.*;我得到 The import com.testmodule cannot be resolve.
猜你喜欢
  • 1970-01-01
  • 2021-08-01
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 2020-11-12
  • 2014-01-10
  • 1970-01-01
  • 2020-04-01
相关资源
最近更新 更多