0

I have a use case where I only want to execute some packages in my SpringBoot application. So, in my main class, I am using something like this -

@SpringBootApplication
@ComponentScan(basePackages = {"com.example"})
public class Example {

  public static void main(String[] args) {
    SpringApplication.run(Example.class, args);
  }
}

So, here I have hardcoded the basePackages as "com.example". This is not what I want. I want to receive the package name when the application is run from the terminal through command-line arguments. Is there a way I can pass command-line arguments to the application and use the arguments that I receive inside the basePackages? Thanks in advance

Trayambak Kumar
  • 113
  • 1
  • 9
  • Are you sure you want/need to do it based on packages? It is easier to assign components to a profile and start with a certain profile to enable/disable a set of Spring components. See https://www.baeldung.com/spring-profiles – Wim Deblauwe Apr 19 '21 at 06:07
  • So, can I pass the value to "spring.profiles.active" through the command line? If yes, can you give me a sample code. Thanks – Trayambak Kumar Apr 19 '21 at 06:20
  • See https://stackoverflow.com/questions/31038250/setting-active-profile-and-config-location-from-command-line-in-spring-boot on how to activate profiles from the command line. – Wim Deblauwe Apr 19 '21 at 06:26

1 Answers1

3

You can use placeholder for this:

@SpringBootApplication
@ComponentScan(basePackages="${scan.myPackage}")
public class Example {
  public static void main(String[] args) {
    SpringApplication.run(Example.class, args);
  }
}

and on terminal, you can do:

java -jar app.jar --scan.myPackage=com.example

You may want to learn about profiles.

Edit:

From Spring Boot 2.x and Maven 3.x and above, the command to supply dynamic values is:

java -jar -Dscan.myPackage=com.example app.jar
adarsh
  • 1,393
  • 1
  • 8
  • 16
  • Excuse me, if I sound stupid. So, this will work for spring-boot as well, right? Also, how can I run if I don't have jar currently? – Trayambak Kumar Apr 19 '21 at 06:25
  • @TrayambakKumar *I want to receive the package name when the application is run from the terminal through command-line arguments*: If you don't have the `jar`, what would be *running* form terminal :) ? – adarsh Apr 19 '21 at 06:35
  • 1
    I wanted something like this(mvn spring-boot:run -Dspring-boot.run.arguments="--scan.myPackage=com.example" ). But your answer showed me the path. Thank you so much – Trayambak Kumar Apr 19 '21 at 07:07