简体   繁体   中英

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. I also want the plugins to have access to all the Spring Boot features, most prominently Spring Data 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.

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.

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. 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.

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?

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.

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.

Find out more at:

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

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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