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

前端 未结 7 1284
闹比i
闹比i 2021-01-31 17:28

Can Spring Boot be used with OSGi? If not, any plans to have an OSGi Spring Boot (Apache Felix or Eclipse Equinox)? In my opinion, cloud applications must be highly modular and

7条回答
  •  南笙
    南笙 (楼主)
    2021-01-31 17:46

    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 .

    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

提交回复
热议问题