简体   繁体   English

在 Spring 引导中动态加载 Spring Bean 和组件

[英]Dynamically loading Spring Beans and Components in Spring Boot

I'm trying to make a Spring Boot app where plugins are loaded dynamically from JARs at runtime.我正在尝试制作一个 Spring Boot 应用程序,其中插件在运行时从 JARs 动态加载。 I also want the plugins to have access to all the Spring Boot features, most prominently Spring Data JPA.我还希望插件能够访问所有 Spring 引导功能,最突出的是 Spring 数据 JPA。 I've already figured out how to load classes from JARs, and now my problem is how to "hook up" the loaded classes (that might be Beans, JpaRepositories etc.) to "work with" my main Spring Boot application.我已经想出了如何从 JARs 加载类,现在我的问题是如何“连接”加载的类(可能是 Beans、 JpaRepositories等)以“使用”我的主要 Spring 引导应用程序。

I also might in the future want to have my own annotation system for doing different things with the main app from the plugins, (that I know how to do using reflection) and I would want to still be able to do it after I manage to sort the Spring stuff out.将来我也可能希望拥有自己的注释系统,用于使用插件中的主应用程序做不同的事情(我知道如何使用反射),并且我希望在我设法之后仍然能够做到这一点整理 Spring 的东西。

I imagine I have to tell Spring somehow to additionally look for @Component s and other meaningful classes from those JARs, when it's scanning for annotations.我想我必须以某种方式告诉 Spring 在扫描注释时从那些 JARs 中额外寻找@Component和其他有意义的类。 I tried with @ComponentScan 's basePackageClasses attribute but that needs to be constant, and hard-coding this is not an option for what I wanna do.我尝试使用@ComponentScanbasePackageClasses属性,但这需要保持不变,并且硬编码这不是我想做的选择。

So is what I want to achieve even possible?那么我想要实现的目标是可能的吗? And if it is, then can I do it through Java code, or is it maybe achievable by writing some XML configs?如果是,那么我可以通过 Java 代码来实现,还是可以通过编写一些 XML 配置来实现?

When you start an spring app, beans are loaded and hooked in its contexts, so if you want to add more to it manually you might need to reload the whole context which may not be a good idea for an spring boot app.当您启动 spring 应用程序时,bean 会在其上下文中加载和挂钩,因此如果您想手动添加更多内容,您可能需要重新加载整个上下文,这对于 spring 启动应用程序可能不是一个好主意。

Instead, I would suggest to use spring profiles, so you can define different configurations and based on what you want you can simple enable the one you need.相反,我建议使用 spring 配置文件,这样您就可以定义不同的配置,并根据您的需要简单地启用您需要的配置。

Find out more at:了解更多信息:

https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-profiles https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-profiles

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM