osgi + felix example2编写

49 篇文章 9 订阅
15 篇文章 1 订阅

在上次博文中配置了karaf的日志格式输出,在两篇之前的一篇文章编写了基本的felix中的简单的example编写,编写了一个简单的Activator,启动并得到正常的输出,这一篇博文将开始稍微复杂一点的程序编写,将进行一个服务的注册。


 DictionaryService

首先创建一个interface,命名为DictionaryService,添加以下内容:

package cn.com.example2;
/**
 * A simple service interface that defines a dictonary service
 * A dictonary service verifies the existence of a word
 */
public interface DictionaryService {

    /**
     * Check for existence of a word.
     * @param word  the word to be checked.
     * @return  true if the word is in the directonary.
     *           false otherwise.
     */
    public boolean checkWord(String word);
}

此处interface的实现,等会直接写在Bundle之中,不单独写一个实现类,之后的每一个Bundle基本都会带着一个内部类实现这个DictionaryService接口。


 Activator类

现在创建一个Activator类,这次仅仅只继承BundleActivator类,实现其中相关方法,并编写内部类DictionaryImpl实现DictionaryService,具体的代码如下:

package cn.com.example2;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

import java.util.Hashtable;

/**
 * Created by Administrator on 2016/6/18.
 */
public class Activator implements BundleActivator {

    public void start(BundleContext context) throws Exception {
        System.out.println("service registering..");
        Hashtable<String, String> props = new Hashtable<String, String>();
        props.put("Language", "English");
        context.registerService(DictionaryService.class.getName(), new DictonaryImpl(), props);
        // DictionaryService service = context.getService();
    }

    public void stop(BundleContext context) throws Exception {

    }

    private static class DictonaryImpl implements DictionaryService {

        String[] m_dictonary = {
                "welcome", "to", "osgi", "tutorial"
        };

        public boolean checkWord(String word) {
            word = word.toLowerCase();
            for (int i = 0; i < m_dictonary.length; i++) {
                if (m_dictonary[i].equals(word)) {
                    return true;
                }
            }
            return false;
        }
    }
}

在上述代码编写中,在Activator中的start方法中,我们进行了服务的注册,就是如下一段代码:

context.registerService(DictionaryService.class.getName(), new DictonaryImpl(), props);

但在本文中仅只对服务进行了注册,但本文并不使用该服务,仅只进行相应的注册。


Bundle运行

现在我们进行相应服务的演示,将当前项目的pom.xml中的felix插件的Bundle-Activator改为当前类之后,将相应项目重新clean,install之后,启动karaf,查看相应结果,如下图:
这里写图片描述
Activator正常启动,相应输出也正常输出,说明服务也正常注册,但本文没有验证相应服务的注册,这个将在下一篇博文中讲解。


 总结

本文编写了一个比上一个example稍微复杂一点的实例,增加一个接口,并注册了这个服务,但在本文具体的程序编写中,并没有演示使用这个服务,或者证明这个服务正常注册,在下一篇博文中将讲解注册式服务和声明式服务,并验证本文中服务正常注册。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值