Configuring base package scan for Spring Boot Application at Runtime

狂风中的少年 提交于 2021-02-07 09:38:00

问题


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.


回答1:


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.




回答2:


Have you tried this:

@SpringBootApplication(scanBasePackages={"path1", "path2"})

Hope this helps :)



来源:https://stackoverflow.com/questions/35856941/configuring-base-package-scan-for-spring-boot-application-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!