我们可以使用Spring Boot实现Java库吗?

xli*_*ves 10 java spring spring-boot

在线程名称的指导下,我想使用Spring Boot创建一个JAVA库.我找到了这个帖子:使用Spring启动创建一个库jar.但是,该线程的目标似乎通过将其实现为REST API来解决.

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

有关更多信息,请参见下面的pom.xml文件片段.根据配置,我不包括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>
Run Code Online (Sandbox Code Playgroud)

mh-*_*dev 12

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

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

第一个是简单的@Configuration,另一个是@Import.

图书馆计划

将一个类放在root包中,看起来像这样.

@Configuration // allows to import this class
@ComponentScan // Scan for beans and other configuration classes
public class SomeLibrary {
    // no main needed here
}
Run Code Online (Sandbox Code Playgroud)

使用该库的其他项目

通常将一个类放在项目的根包中.

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

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