首页 > 解决方案 > 如何使用 aries blue print 在 Web 应用程序中将 apache karaf 捆绑作为服务注入?

问题描述

我有 servlet Web 应用程序,并希望使用 aries 蓝图将 apache karaf 捆绑作为服务注入到 Web 应用程序中。

这些是注入捆绑包所遵循的步骤:

1) 在 blueprint.xml 示例代码中添加了带有 id 和 interface 值的引用标记在这里

<reference id="jsonStore" interface="com.test.test.jsonstore.service.JsonClientStore" />

2) 添加了带有 ref 属性作为参考 id 的 bean 标记,用于捆绑我们在 blueprint.xml 文件中注入的内容。示例代码在这里

<bean id="echo" class="com.test.test.core.jsonrequest.JsonServlet">
     <property name="jsonStore" ref="jsonStore"/>
   </bean>

3) blueprint.xml 文件位置作为上下文参数标记 web.xml。示例代码在这里

<context-param>
      <param-name>blueprintLocation</param-name>
      <param-value>OSGI-INF/blueprint/blueprint.xml</param-value>
    </context-param>

4) 在web.xml 中添加listner 类。示例代码在这里

<listener>
      <listener-class>org.apache.aries.blueprint.web.BlueprintContextListener</listener-class>
    </listener>

5) @Inject 注解,用于在 servlet 类中注入特定的包。示例代码在这里

@Inject(ref="jsonStore")
    JsonClientStore jsonStore = null;

以下链接供参考文档 http://aries.apache.org/modules/blueprintweb.html

仍然没有注入捆绑包,请有人可以帮忙吗?

如何将这些 karaf 包作为服务注入 servlet 应用程序?

标签: javaapache-karafblueprint-osgiaries

解决方案


我在没有使用 aries 蓝图的情况下解决了上述问题。

我在 servlet 中添加了以下方法以获取注入的捆绑包,我将捆绑包名称作为 serviceName 参数发送到以下方法,这将发送回注入捆绑包所需的服务,通过使用该服务,我将使用该服务中存在的方法.

private <T> T getService(Class<T> serviceName) {
        Bundle bundle = FrameworkUtil.getBundle(serviceName);
        if ( bundle == null ) {
            return null;
        }       
        BundleContext bundleContext = bundle.getBundleContext();
        ServiceReference serviceRef = bundleContext.getServiceReference(serviceName);  
        if (serviceRef == null)          
            return null;
        return (T) bundleContext.getService(serviceRef);
    }

这段代码解决了我的问题。


推荐阅读