基于OSGi的企业级开发框架实践――OSGi Annotations(一)

2014-11-24 11:49:58 · 作者: · 浏览: 36
在Bundle中要使用OSGi Annotation,首先要定义两个BeanPostProcessor。之前的文章中我们已经看过了,这里我们再来看一下,如下图所示:
(图一)
以上两个Bean均继承至org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter,目的是为了在Spring实例化上下文中的每个Bean时可以执行附加的操作,在这里我们就是要拦截在Spring上下文中初始化的每个Bean是否存在OSGi服务的Annotation,如果存在,则将此Bean注册为一个OSGi服务并登记到OSGi容器中。如果是对一个OSGi服务的引用,则会查找OSGi容器中所对应的服务,然后将其注入到当前的Bean中。其实工作原理还是比较简单易懂的。不过要记住,为了在某个Bundle中使用OSGi Annotation,必须要在当前Bundle的Spring XML中定义这两个后置Bean处理器。当我们配置完这两个Bean后,我们就可以在类中编写如下的代码:
首先我们在biz-share Bundle中编写一个接口:
[java]
[java]
package org.storevm.helloworld.biz.share;
/**
*
* @author Administrator
* @version $Id: OsgiServiceTest.java, v 0.1 2013-2-27 下午12:49:00 Administrator Exp $
*/
public interface OsgiServiceTest {
/**
* 输出
*/
void out();
}
然后编写一个实现类:
[java]
package org.storevm.helloworld.biz.share;
import org.apache.log4j.Logger;
import org.storevm.eosgi.core.annotation.OsgiService;
import org.storevm.eosgi.core.utils.LogUtils;
/**
*
* @author Administrator
* @version $Id: OsgiServiceTestImpl.java, v 0.1 2013-2-27 下午12:53:24 Administrator Exp $
*/
@OsgiService(interfaces = { OsgiServiceTest.class })
public class OsgiServiceTestImpl implements OsgiServiceTest {
private static final Logger LOGGER = Logger.getLogger(OsgiServiceTest.class);
/**
* @see org.storevm.helloworld.biz.share.OsgiServiceTest#out()
*/
@Override
public void out() {
LogUtils.info(LOGGER, "这是一个OSGi服务, name={0}", OsgiServiceTest.class);
}
}
注意在类的起始处,我们定义了如下的Annotation:
[java]
@OsgiService(interfaces = { OsgiServiceTest.class })
通过这个Annotation,我们就可以将OsgiServiceTestImpl注册为一个OSGi服务了。为了让后置Bean处理器起作用,我们需要将OsgiServiceTestImpl注册到Spring的上下文中,如下配置所示(在bundle-context.xml文件中定义):
[ html]
至此我们的OSGi服务就算发布完成了,我们不再需要配置元素。在Eclipse IDE中启动OSGi运行时容器,我们可以看到在Console中显示的如下日志信息:
(图二)
我们可以看到,OsgiServiceTest已经被成功发布为一个OSGi服务了。不过问题还没有结束,我们只是发布了一个OSGi服务,但是其他的Bundle还不知道这个OSGi服务的存在,因此为了让其他Bundle可以使用这个服务,我们还必须将服务暴露出去,请打开biz-share Bundle中的MANIFEST.MF文件,并切换到“Runtime”选项卡。如下图所示:
(图三)
我们点击“Add”按钮,在弹出的对话框中选择需要导出的Package,然后点击“OK”按钮,如下图所示:
(图四)
最后结果如下图所示:
(图五)
最后请点击工具栏上保存按钮,至此我们已经将org.storevm.helloworld.biz.share包暴露出来,可供其他Bundle引入了。
接下去我们在biz-service-impl Bundle中引入biz-share Bundle发布的OSGi服务。请打开biz-service-impl Bundle中的MANIFEST.MF文件并切换到Dependencies选项卡下,如下图所示:
(图六)
从图六中我们可以发现,biz-share Bundle已经被开发框架默认配置成Required Bundle了,所以我们无需再导入该Bundle,请关闭MANIFEST.MF文件。在biz-service-impl Bundle中编写一个接口,如下所示:
[java]
package org.storevm.helloworld.biz.service.impl;
/**
*
* @author Administrator
* @version $Id: InvokeOsgiServiceTest.java, v 0.1 2013-2-27 下午1:21:37 Administrator Exp $
*/
public interface InvokeOsgiServiceTest {
/**
* 调用
*/
void invoke();
}
然后再编写一个实现类,如下所示:
[java]
package org.storevm.helloworld.biz.service.impl;
import org.storevm.eosgi.core.annotation.ServiceReference;
import org.storevm.he