Search code examples
javaspringtomcat

Configuring base package scan for Spring Boot Application at Runtime


I'm running a Spring Boot Application within a Tomcat instance packaged as a war file. I would like to be able to add "packages" to my instance in the form of rest services. To that end I need to be able to configure scanBasePackages in the @SpringBootApplication annotation at runtime. i.e. when tomcat starts up. For now I have ...

@SpringBootApplication(scanBasePackages="path1, path2")
public class RestApplication extends SpringBootServletInitializer {
   //code
}

...but I would like to have path2 be configurable and alternately be able to add path3, etc. if desired. How can I achieve this? I understand that I can't configure the String in the annotation so my question is about what other alternatives I have to this annotation for setting this.

Cheers.


Solution

  • you can try to use something like this in your project

    @Configuration
    @Profile("custom-profile")    
    @ImportResource( {"file:path/additional-context.xml" } )  
    public class ConfigClass { }  
    

    and configure additional packages scanning in this file then.

    <context:component-scan base-package="x.y.z.service, x.y.z.controller, x.y.z.dao" />
    

    Note, your resource additional-context.xml declared as external and you have ability to change it without rebuilding war at all.

    @ImportResource will be handled after declaring profile "custom-profile" as active. It's a safe way for starting application with "default configuration" without any "additional-context.xml" file of disk.