众所周知,使用Spring的一大好处就是它提供了一个简单的基于Bean的编程模型(采用IoC和AOP设计模式),不过随之而来的也有不好的副作用——那就是我们很容易就陷入了XML配置漩涡。自从JDK1.5之后,Spring提供了注解的方式,大大减少了XML的配置量。不过在Spring的OSGi版本中(Spring DM)XML配置漩涡依旧存在,OSGi服务的注册和引入都需要大量的XML配置,一旦遗漏则整个OSGi程序就无法正确运行。之前我还专门写过一篇文章《在Spring DM中使用Annotations发布和引用服务》,大致介绍了在Spring DM中如何使用Annotation来简化OSGi的使用,有兴趣的同学可以先去阅读一下这篇文章。在基于OSGi的企业级开发框架中,我们自然而然的也会引入Annotation,因为开发框架依旧是基于Spring DM的。接下去我们通过一个具体的实例来说明如何使用OSGi Annotation。
在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] view plaincopyprint?
[java] view plaincopyprint?
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();
}
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] view plaincopyprint?
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);
}
}
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);
}
}更多精彩教程请关注:win7旗舰版下载