Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share Repository and Service classes between 2 projects

I am working on 2 projects, one web app (Spring MVC) and one standalone backend service application (Spring boot) that heavily interact together. I am using hibernate for both and they are both coded using the Netbeans IDE.

My "issue" is that i end up with duplicate code in both project, mainly in the Repository and Service layers. My entities are obviously also duplicated since both projects use the same database.

Is there a way to make some sort of class library (a third project maybe?) and put all the common code in there? If that is indeed possible, how do you then change each project so they can still access this code as if it were part of them? I was thinking of putting all my Repositories, Services and entities in there to avoid code duplication and greatly reduce the risk of error.

Thank you!

like image 436
Martin Avatar asked Oct 17 '25 16:10

Martin


1 Answers

Separate those Repository and Service classes to a submodule.

The structure looks like:

-- your app
  -- api    (dependent on `common` module)
  -- webapp (dependent on `common` module)
  -- common

Then the problem is to initialize beans inside common module. AFAIK, you have two options:

  1. In @Configuration class of api or webapp module, add base packages of common module to component scan packages
  2. In api or webapp resources folder, add Spring configuration factory /src/main/resources/META-INF/spring.factories org.springframework.boot.autoconfigure.EnableAutoConfiguration=your.path.AutoConfiguration

    Define service/repository @Bean inside AutoConfiguration class

like image 194
Mạnh Quyết Nguyễn Avatar answered Oct 20 '25 07:10

Mạnh Quyết Nguyễn