0

We have several classes annotated with the @Component notation in our Spring Boot 2.x project - but we would like to selectively pick only one of these class at runtime.

To further elaborate we created a Uber Jar - which will run on several machines - but each jar should be running a different logic and this logic is dictated by one of this class.

What is the cleanest way to achieve this in Spring boot 2.x? I read something about profiles etc. any cleaner solutions are very much appreciated.

BDL
  • 21,052
  • 22
  • 49
  • 55
Durga Deep
  • 437
  • 2
  • 6
  • 14
  • Possible duplicate of [How do I tell Spring Boot which main class to use for the executable jar?](https://stackoverflow.com/questions/23217002/how-do-i-tell-spring-boot-which-main-class-to-use-for-the-executable-jar) – sofend Nov 25 '18 at 20:06
  • Maybe you're looking for: https://docs.spring.io/spring-boot/docs/current/maven-plugin/usage.html and then https://docs.spring.io/spring-boot/docs/current/reference/html/executable-jar.html#executable-jar-launcher-manifest in the latter take a look at the Launcher Manifest and how it is used in the PropertiesLauncher Once you select that launcher you can then directly specify the Main class to run via the loader.main property. – sofend Nov 25 '18 at 20:09

2 Answers2

0

Use the Spring Boot Maven plugin, and configure it to use the PropertiesLauncher, then set the loader.main via the command line. Or, you can specify the whole thing via the command line. Assuming you're using the Maven (or Gradle) Spring Boot plugin to build the jar/war file:

java -cp bootApp.jar -Dloader.main=org.your.package.DemoApplication org.springframework.boot.loader.PropertiesLauncher
sofend
  • 647
  • 8
  • 17
0

You can group and move those @Component classes in multiple @Configuration classes. In this case you have to manually declare them as @Beans (methods). You will define as many @Configuration classes as your machines count.

Further on, you can enable or disable configuration classes by means of Spring Profiles. Profiles are enabled using spring.profiles.active system property (-Dspring.profiles.active=profile1,profile2).

If you want to have it clean then you have to do it in 'Dependency Inversion Principle' way: You should define interfaces for your @Components and each @Configuration will declare @Beans of a concrete type. In this way you can use @Autowired dependency injection w/o knowing the concrete implementation.