简体   繁体   中英

How to reuse classes in a Spring Boot REST application?

I have a Spring Boot REST application with JPA entities and Repository classes (and related services) that works very well. Now I would like to reuse these classes for other purposes, like weekly CRON jobs and similar one-time processes which will be run from the command line.

What would be the best way to do this? The challenge is that the persistence context properties are set in application.properties, and the persistence context isn't initialized unless the Application class is initialized.

I can break out all of these classes into a separate project, and use a different way to define the persistence context there, but this becomes more of a maintenance headache if anything changes with the entities or DAO methods.

What I would really like is to have a way, from the command line, to tell Spring Boot to run another class instead of the main Application (and have the persistence context properly initialized). Any way to do this?

(Note I asked a similar question which got no response: Possible to use Spring Boot repositories from another main class? )

[Edit] is it possible to do this by creating a @component that implements the CommandLineRunner? I just want it to run a simple one-time process and not the full REST application.

There are a number of ways you could do this. You can have multiple Main classes, and then select which application yuo want to start select main class , however if you don't know how ComponetScan works you will end up loading both applications if you are not careful.

Another way is to use Profiles , you can set the profile when you start your spring app, and then have your web profile that will start Tomcat, and a command line profile that will not .

In the project I'm working on we have choosen to have the data-layer as a completly separate module (same gradle project), which has it's own Spring Context. The data-layer spring context is then used as the parent context for other applications, as a reusable component. It is a somewhat cleaner separations of concerns, were the shared code is clearly marked, instead of having multiple applications inside the same code mudule.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM