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/