Tuesday, 21 April 2020

How to Generate JAR and Use as dependency in Spring Boot

For Generating Jar File-

You can extend your project by maven-assembly-plugin.

What is Assembly Plugin-

An "assembly" is a group of files, directories, and dependencies that are assembled into an archive format and distributed. For example, assume that a Maven project defines a single JAR artifact that contains both a simple application and a web application. Such a project could define two "assemblies" that bundle the application with a different set of supporting scripts and dependency sets. One assembly would be the assembly for the simple application, and the other assembly could be a web application bundled with a slightly different set of dependencies. for more about assembly plugin click here

<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.1.0</version>
        <configuration>
        <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
        </configuration>
        <executions>
        <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
            <goal>single</goal>
            </goals>
            </execution>
        </executions>
</plugin>

Include these line in your pom.xml and make build of it by using maven command -

mvn package

After the build you will get 3 jars. The main one will be the same as a usual Maven project, while the second one will have the classifier appended with exec and be the executable JAR. The third jar name will be appended by jar-with-dependencies and will contain your classes with classes added as dependencies in your spring boot application(spring-boot-starter-web, thymeleaf,...), so into the pom of the application where you want to add that project as dependencies you won't have to add dependencies from spring boot project.

Include Generated Jar In your another project -

Steps for adding external jars in IntelliJ IDEA:

  1. Click File from the toolbar
  2. Project Structure (CTRL + SHIFT + ALT + S on Windows/Linux, ⌘ + ; on Mac OS X)
  3. Select Modules at the left panel
  4. Dependencies tab
  5. '+' → JARs or directories
Happy Coding