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

时间:2016-03-04 07:38:13

标签: java spring spring-boot

在线程名称的指导下,我想使用Spring Boot创建一个JAVA库。我找到了这个帖子:Creating a library jar using Spring boot。但是,该线程的目标似乎是通过将其实现为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>

1 个答案:

答案 0 :(得分: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
}

使用图书馆的其他项目

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

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

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