osgi - Spring Boot 可以与 OSGi 一起使用吗?如果没有,是否有计划使用 OSGi Spring Boot?

标签 osgi spring-boot

Spring Boot 可以与 OSGi 一起使用吗?如果没有,是否有计划使用 OSGi Spring Boot(Apache Felix 或 Eclipse Equinox)?在我看来,云应用程序必须像 OSGi 提供的那样高度模块化和可更新。

最佳答案

我认为值得将其作为单独的答案发布(并非每个人都会阅读所有对答案的评论)。

@StasKolodyuk 的优秀解决方案提供了一种在 OSGI 环境中运行 Spring Boot 应用程序的方法。

但有限制:Spring Boot 的注解自动映射不起作用,因为在 OSGI 中运行时缺少包扫描支持。

这是另一个技巧,它最终允许从您的代码中自动获取带有组件的 Spring Boot 应用程序在 OSGI 中运行(我在 Karaf 中测试过)。

功能示例可在 https://github.com/dimmik/osgi-spring-boot-demo 获得

诀窍是为 SpringApplication 实例提供适当的 ResourcePatternResolver :

package by.kolodyuk.osgi.springboot;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.osgi.io.OsgiBundleResourcePatternResolver;

@SpringBootApplication
public class SpringBootBundleActivator implements BundleActivator {

    ConfigurableApplicationContext appContext;

    @Override
    public void start(BundleContext bundleContext) {
        // Set context classloader (main trick, to enable SpringBoot start at the first place)
        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        // trick to enable scan: get osgi resource pattern resolver
        OsgiBundleResourcePatternResolver resourceResolver = new OsgiBundleResourcePatternResolver(bundleContext.getBundle());
        // and provide it to spring application
        appContext = new SpringApplication(resourceResolver, SpringBootBundleActivator.class).run();
    }

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

    public static void main(String[] args) {
        SpringApplication.run(SpringBootBundleActivator.class);
    }
}

关于osgi - Spring Boot 可以与 OSGi 一起使用吗?如果没有,是否有计划使用 OSGi Spring Boot?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30881786/

相关文章:

java - 无法获取 OSGi 服务的工作引用

OSGi 到 Spring Boot

java - 访问资源文件夹中的文件

spring - 使用Keycloak和spring boot实现 Multi-Tenancy 应用程序

java - 我可以使用哪个框架在网络应用程序中进行插件处理

java - OSGi 应用程序如何在 Java 9 上运行?

java - 使用 OSGi 启动 JUnit 测试时出现 IllegalStateException

spring-boot - Spring Boot Web 服务器在 Eclipse 中运行良好,无法在服务器 : missing EmbeddedServletContainerFactory bean 上启动

spring-boot - 如何在 bitbucket 上设置基于 java 11 的 spring boot 管道?

java - 将 Web Controller 添加到 Akka Actor 系统