简体   繁体   中英

Loading Spring beans from library without importing configuration file?

I have a Spring Boot application. I have several customers who each have a version of this application, with a few custom @Component , @Service , etc, classes. I am trying to abstract those custom Spring beans out into library jars which I can place on the classpath and load dynamically.

For example, suppose I have an interface in my core library:

public interface MyInterface {
    String doSomething();
}

I have a different implementations of MyInterface in my customer-specific libraries, all annotated with @Component .

I want to be able to put

@Autowired
List<MyInterface> components;

in my main application.

Then, I want to just place my main application in a folder with the appropriate customer's library (or multiple) and run it with

java -cp . -jar my-application.jar

and have that @Autowired pick up the customer's specific components.

Is this possible? I don't want to use @Import in the main application, because that requires knowing which customer's library is being loaded.

I did figure this out. Here is a demo project for loading @Component objects from plugins at runtime.

https://github.com/imnotpete/plugin-demo

It uses the loader.properties file to specify a folder to add to the classpath, and then @ComponentScan can include any jars from that folder when autowiring.

loader.properties:

loader.path=plugins

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