java 在运行时为 Spring Boot 应用程序配置基本包扫描
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35856941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Configuring base package scan for Spring Boot Application at Runtime
提问by crowmagnumb
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 ...
我在打包为 war 文件的 Tomcat 实例中运行 Spring Boot 应用程序。我希望能够以休息服务的形式将“包”添加到我的实例中。为此,我需要能够在运行时在 @SpringBootApplication 注释中配置 scanBasePackages。即当 tomcat 启动时。目前我有...
@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.
...但我希望 path2 是可配置的,并且如果需要,还可以添加 path3 等。我怎样才能做到这一点?我知道我无法在注释中配置字符串,所以我的问题是关于设置此注释的其他替代方法。
Cheers.
干杯。
回答by ivanenok
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.
请注意,您的资源 additional-context.xml 声明为外部资源,您可以更改它而无需重建War。
@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.
@ImportResource 将在将配置文件“custom-profile”声明为活动后处理。这是一种使用“默认配置”启动应用程序而无需任何“additional-context.xml”磁盘文件的安全方式。
回答by Andrés S.
Have you tried this:
你有没有试过这个:
@SpringBootApplication(scanBasePackages={"path1", "path2"})
Hope this helps :)
希望这可以帮助 :)