Nick Grealy Nick Grealy - 5 months ago 10
Java Question

Spring-boot > implicitly auto register a 3rd party bean

This may be an impossible task, but here goes...

Is it possible to register a spring bean, by (ONLY) adding a jar to the classpath of a
spring-boot
application?



Scenario: I would like to create a non-intrusive
plugin
jar, which when imported into a
spring-boot
project's classpath, will automatically be picked up and provide a service (e.g. via a
RestController
).

Constraints




  • I don't want to change or reconfigure the existing
    spring-boot
    application (i.e. no additional scan paths or bean config).

  • I don't have any knowledge of the target
    spring-boot
    application's package structure/scan paths.



I guess I was hoping that by default Spring scan's its own package structure (i.e.
org.springframework.**
looking for the presence of database libs, etc) and I could piggy-back off that - I haven't had any luck (so far).

I've setup an example project in github, to further clarify/illustrate my example and attempts.

** Solution Addendum **



This bit that got it working, was to add the following file, which points to an
@Configuration
config file...

plugin-poc\src\main\resources\META-INF\spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.thirdpartyplugin.PluginConfiguration

Answer

I think in such cases you would try to add a spring auto configuration that is annotated with @ConditionalOnClass to be only evaluated if the given class is on the classpath. This class can register the bean and would just be evaluated if the conditional evaluates to true

Here is the relevant part of the spring boot documentation : Creating your own auto-configuration