Can Spring Boot be used with OSGi? If not, any plans to have an OSGi Spring Boot?

Yes, it’s possible to run Spring Boot apps in OSGI container.

First of all, you’ll have to switch from Spring Boot jar packaging to OSGI bundle.

If you’re using Maven you can use org.apache.felix:maven-bundle-plugin for doing that.
As Spring Boot dependency jars are not valid OSGI bundles, we should either make them valid bundles with bnd tool or we can embed them into the bundle itself. That can be done with maven-bundle-plugin configuration, particularly with <Embed-Dependency>.

However, we need to start the bundle with Spring Boot app somehow. The idea is to start Spring Boot in BundleActivator:

@Import(AppConfig.class)
@SpringBootConfiguration
@EnableAutoConfiguration
public class SpringBootBundleActivator implements BundleActivator {

    ConfigurableApplicationContext appContext;

    @Override
    public void start(BundleContext bundleContext) {
        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        appContext = SpringApplication.run(SpringBootBundleActivator.class);
    }

    @Override
    public void stop(BundleContext bundleContext) {
        SpringApplication.exit(appContext, () -> 0);
    }
}

You should also set context classloader to an OSGI classloader loading the bundle by Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());.
That is required because Spring uses context classloader.

You can see this in action in my demo repo: https://github.com/StasKolodyuk/osgi-spring-boot-demo

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)