【问题标题】:Can we implement a Java library by using Spring Boot?我们可以使用 Spring Boot 实现 Java 库吗?
【发布时间】:2016-06-17 20:41:25
【问题描述】:

按照线程名称的指导,我想使用 Spring Boot 创建一个 JAVA 库。我找到了这个帖子:Creating a library jar using Spring boot。但是,该线程的目标似乎可以通过将其实现为 REST API 来解决。

目前,我正在使用 Spring Boot 开发基于 Spring 的 JAVA 库。而且,我尝试将其打包为 jar 文件,并让另一个 JAVA 应用程序在 JAVA 库方面使用它。不幸的是,我发现当调用者应用程序调用添加的库的某些方法时,在库中定义的配置根本不起作用。 它还显示类似“CommandLineRunner 不存在”的错误。

有关更多信息,pom.xml 文件的 sn-p 如下所示。根据配置,我不包含web应用的依赖。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.3.RELEASE</version>
</parent>

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

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    如果以正确的方式设计,这根本不是问题。但具体而言,这取决于您使用的功能。由于 Spring 支持 JPA、Websocket 等外部库..

    开发一个库并在另一个项目中使用它有两个重要的注解。

    第一个是@Configuration,另一个是@Import

    图书馆项目

    在根包中放置一个类似这样的类。

    @Configuration // allows to import this class
    @ComponentScan // Scan for beans and other configuration classes
    public class SomeLibrary {
        // no main needed here
    }
    

    使用该库的其他项目

    通常在项目的根包中放置一个类。

    @SpringBootApplication
    @Import(SomeLibrary.class) // import the library
    public class OtherApplication {
        // just put your standard main in this class
    }
    

    重要的是要记住,根据您在其他框架方面使用的内容,可能需要做其他事情。 例如,如果您使用 spring-data@EntityScan 注释会扩展休眠扫描。

    【讨论】:

    • 非常感谢您的清晰解释。那么,根据您的建议,其他项目也必须是基于Spring的应用程序?另外,如果可能,您能否更正您的示例,因为这两个类具有相同的名称?
    • 更正抱歉是复制粘贴失败。如果您想这样做,那么“其他”应用程序也必须是 spring 应用程序。可以创建某种自包含库,但这在 Stackoverflow 帖子中更复杂且难以解释。 (我会避免这种方法)
    • 谢谢。也许,我稍后可能会通过其他渠道(例如电子邮件)向您询问解决方案。假设我将把库项目和另一个项目都制作为 Spring Boot 应用程序。那么,如何将库jar添加到其他项目
    • 创建一个 Maven 工件并引用它,因为依赖关系很可能是最佳选择。如果您只是想在本地开发它,请使用“mvn install”将库安装在本地 maven 存储库中,然后将其作为依赖项添加到“其他”项目中。如果有任务随时问。我认为我的个人资料中有一封电子邮件。如果此问题已完成,请将答案除外,以将问题标记为已完成。
    • 抱歉,如果可能的话,您能否逐步指导我如何创建一个 Maven 工件并作为依赖项引用。如果没有,请给我一些网址供我自学。顺便说一句,我完全同意你的解释。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 2017-09-01
    • 2020-06-04
    • 2020-01-14
    • 1970-01-01
    • 2021-02-19
    • 2016-09-11
    相关资源
    最近更新 更多