0

I have a Spring Boot 2.1 web application. It works great. I can package it as either a WAR or a JAR. In my pom.xml file I use:

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

This application has many entity classes and quite a few Spring Data repositories. Almost always we deploy it as a WAR file.

Here's the question: sometimes we need to do a command line or batch process on our database. For example, we might want to run a process to resize all the images which are stored in the database, and that should be run by an administrator from the command line.

It would be great if mvn install would install a JAR file in the local Maven repository and I could use that artifact in another project to access my entity and repository definitions. I've tried many things, but whenever I build my project as a JAR file, and I look at the JAR, all my classes are within BOOT-INF/classes, which doens't allow them to be referenced from another project.

I was able to fix that by using a repackage goal in the spring-boot-maven-plugin. However, when I did that, it did generate a jar file but my CLI application couldn't start correctly with the repository beans created.

I read in the Spring Boot documentation:

Like a war file, a Spring Boot application is not intended to be used as a dependency. If your application contains classes that you want to share with other projects, the recommended approach is to move that code into a separate module. The separate module can then be depended upon by your application and other projects.

Is there any simpler way to do this, such that I don't have to create yet another project and manage that? Or is it a good practice to have a separate project for entities and Spring Data repositories?

user2959589
  • 362
  • 1
  • 9
  • 23

1 Answers1

0

So, in short words you just want to have a library with your entity and repositories? Then it should be enough to configure a simple maven project, a standard one, not inheriting from Spring Boot.

As spring Boot uses Spring Data JPA under the covers, you just need Spring Data JPA declarations, so add the dependency marking it as provided.

<dependencies>
  <dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>Some reference version<version>
    <scope>provided<scope>
  </dependency>
<dependencies>

This allows not to make the project include the Spring Data JPA dependency itself, as it will be included by the end project, which uses Spring Boot. However, you'll need to declare a reference version to use, you could take the one your current Spring Boot project uses (you can have a look in the maven dependency tree).

https://spring.io/projects/spring-data-jpa

Difference between maven scope compile and provided for JAR packaging

Aritz
  • 30,971
  • 16
  • 136
  • 217