Osgi Karaf PaxExam正在获取java.lang.IllegalStateException:无效的BundleContext

Osgi Karaf PaxExam正在获取java.lang.IllegalStateException:无效的BundleContext,osgi,apache-karaf,osgi-bundle,karaf,blueprint-osgi,Osgi,Apache Karaf,Osgi Bundle,Karaf,Blueprint Osgi,您好,我正在运行时使用FeatureService和BundleContext加载一些功能和捆绑包。所有这些东西都已成功加载。之后,如果我对bundlecontext对象执行操作,我将得到 java.lang.IllegalStateException:无效的BundleContext @Inject FeaturesService service; @Before public void init() throws Exception{ service.installFeature("

您好,我正在运行时使用FeatureService和BundleContext加载一些功能和捆绑包。所有这些东西都已成功加载。之后,如果我对bundlecontext对象执行操作,我将得到 java.lang.IllegalStateException:无效的BundleContext

@Inject
FeaturesService service;
@Before
public void init() throws Exception{
    service.installFeature("hibernate");
    service.installFeature("hibernate-validator");
    service.installFeature("transaction");
    service.installFeature("jpa");
    service.installFeature("hibernate-envers");
    service.installFeature("hibernate-envers");
    bc.installBundle("wrap:mvn:com.oracle/ojdbc6/11.2.0").start();
    service.installFeature("DBHandler");
    bc.getBundle(); // Fails
}

经过多次浏览,我了解到您需要刷新捆绑包。如何以编程方式执行此操作并获取refeshed bundleContext对象当您使用无效的捆绑包时,会出现此异常:它已停止或刷新(刷新停止捆绑包并启动新实例)

默认情况下,当您安装一个功能时,Karaf会尝试定义一个要刷新的捆绑包列表,因为有了新的功能。例如,如果一个包对一个包有可选的依赖关系,并且新功能添加了这个包,那么这个包将被刷新,以便更新他的线路。这是可传递的:所有依赖的bundle也会刷新

此外,当您使用“wrap”协议时,它会通过导入所有使用过的打包文件(解析为“可选”)从jar创建一个包

在您的情况下,我假设特性“DBHandler”添加了一个包,该包由您的bundle使用

你可以:

  • 安装这些功能后,使用BundleContext.getBundles()通过SymbolicName查找捆绑包:您将拥有一个有效捆绑包的实例
  • 使用选项
    NoAutoRefreshBundles
    在安装功能时禁用刷新(
    featureService.installFeature(“..”,EnumSet.of(featureService.NoAutoRefreshBundles))
    )。但这不是一个好主意,因为一些捆绑包不会看到新的包

此代码修复了我的问题

public  void refreshBundles() { 

        Bundle currentBundle = FrameworkUtil.getBundle(MyTest.class); 
        if (currentBundle == null) { 
            return; 
        } 

        BundleContext bundleContext = currentBundle.getBundleContext(); 
        if (bundleContext == null) { 
            return; 
        } 

        Bundle systemBundle = bundleContext.getBundle(0); 
        if (systemBundle == null) { 
            return; 
        } 

        FrameworkWiring frameworkWiring = systemBundle.adapt(FrameworkWiring.class); 
        frameworkWiring.refreshBundles(null); 
        bc = frameworkWiring.getBundle().getBundleContext();
    } 

Jermie我找到了一种方法来刷新和更新bundleContext,它解决了我的问题。如果有人希望使用Jérémie解决方案,请在
FeaturesService.Option
中查找枚举,而不是简单地
FeaturesService