码迷,mamicode.com
首页 > 其他好文 > 详细

osgi + felix example2编写

时间:2016-06-25 08:29:19      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

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

osgi + felix example2编写

标签:

原文地址:http://blog.csdn.net/u012734441/article/details/51757025

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!