xlives xlives - 1 year ago 170
Java Question

Can we implement a Java library by using Spring Boot?

As guided by the thread's name, I would like to create a JAVA library by using Spring Boot. I have found this thread: Creating a library jar using Spring boot. However, that thread's objectives seem to be solved by implementing it as a REST API.

Currently, I am developing a Spring-based JAVA library by using Spring Boot. And, I have tried to package as a jar file and let another JAVA application to use it in term of a JAVA library. Unfortunately, I found that when the caller application invokes some methods of the added library, configurations which are defined inside the library do not work at all.
It also shows an error like "CommandLineRunner does not exist".

For more information, a snippet of the pom.xml file is shown below. According to the configuration, I do not include dependencies for web applications.




Answer Source

When designed in the correct way this should not be a problem at all. But in detail it depends which features you're using. Since Spring supports external library like JPA, Websocket,..

There are two important annotations to develop a library and use it in another project.

The first one is simply @Configuration and the other one is @Import.

Libray Project

Put a class in the root package which looks something like this.

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

Other Project using the library

As usually put a class in the root package of your poject.

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

It is important to keep in mind, that other things might be necessary depending on what your using in terms of other frameworks. For example if your using spring-data the EntityScan annotation extends the hibernate scan.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download