---
title: "OSGi原理与最佳实践——字典服务declarative Service实现"
author: "fokman"
date: "2015-09-15T10:11:11Z"
tags: []
categories: ["企业架构"]
slug: "osgi-declarative-service"
draft: false
lastmod: "2015-09-15T10:11:11Z"
id: 2243492
url: "https://fokman.iteye.com/blog/2243492"
---

一、重构DictQueryProject 删除Activator类

二、删除LocalDictQuery里面的Activator类，新建文件夹OSGI-INF，在此文件夹里面创建一个component.xml文件。

 ![](http://dl2.iteye.com/upload/attachment/0111/7109/f7e1b492-3e4d-3d89-be8c-77f609371164.png)

 修改component.xml内容如下：

```
<?xml version="1.0" encoding="UTF-8"?>
<component name="DictQueryService">
	<implementation
		class="com.grocal.localdictquery.local.impl.LocalDictQueryServiceImpl" />
	<service>
		<provide interface="com.grocal.dictquery.query.QueryService" />
	</service>
</component>
```

 implementation标记：指定接口的实现类

service标记：接口的定义类

同理修改DictWeb里面的DictServlet，删除BoundContext相关的应用，修改后的DictServlet如下：

```
package com.grocal.dictweb.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;

import com.grocal.dictquery.query.QueryService;

public class DictServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private QueryService queryService;
	private HttpService httpService;


	public void setHttpService(HttpService httpService) {
		this.httpService = httpService;
		try {
			httpService.registerServlet("/dict/queryServlet", this, null, null);
			httpService.registerResources("/dict/page", "page", null);
			System.out.println("注册service /dict/page/dictquery.html");
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (NamespaceException e) {
			e.printStackTrace();
		}
	}

	public void unsetHttpService(HttpService httpService) {
		if (httpService != this.httpService) {
			return;
		}
		this.httpService.unregister("/dict/queryServlet");
		this.httpService.unregister("/dict/page");
		System.out.println("取消service注册");
		this.httpService = null;
	}

	public void setQueryService(QueryService queryService) {
		this.queryService = queryService;
	}

	public void unsetQueryService(QueryService queryService) {
		if (queryService != this.queryService) {
			return;
		}
		this.queryService = null;
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doPost(req, resp);
		doGet(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doGet(req, resp);
		String queryWord = req.getParameter("query_word");
		resp.setContentType("text/html;charset=utf-8");
		ServletOutputStream output = resp.getOutputStream();
		if (queryService == null) {
			output.println("No available dictquery service");
			output.close();
			return;
		}

		try {
			output.println("Result is " + queryService.query(queryWord));
			output.close();
			return;
		} catch (Exception e) {
			output.println("Error occurs");
			output.println(e.toString());
			output.close();
			return;
		}
	}

}
```

 component的内容如下：

```
<?xml version="1.0" encoding="UTF-8"?>
<component name="DictQueryServlet">
	<implementation class="com.grocal.dictweb.servlet.DictServlet" />
	<reference name="QueryService" interface="com.grocal.dictquery.query.QueryService" bind="setQueryService"
	 unbind="unsetQueryService" policy="dynamic" cardinality="0..1"/>
	<reference name="HttpService" interface="org.osgi.service.http.HttpService" bind="setHttpService" 
	 unbind="unsetHttpService" policy="dynamic"/>
</component>
```

 运行工程，在这里值得注意的一点是需要加入另外两个bundle，以及设置bundle的start level 为2![](http://dl2.iteye.com/upload/attachment/0111/7115/a5a8f238-ccb8-3b02-a858-3e27bd758747.png)