---
title: "OSGI中启动spring dm加载的commons-logging问题"
author: "Fly_m"
date: "2010-05-28T14:09:48Z"
tags: []
categories: ["编程语言"]
slug: "osgi-spring-dm-commons-logging"
draft: false
lastmod: "2010-05-28T14:49:01Z"
id: 677873
url: "https://flym.iteye.com/blog/677873"
---

在进行osgi学习的过程中，首先就是启动一个用springdm编写的hello world程序，当加入了相应的spring包时，启动osgi，其中会报一个错误，即找不到org.apache.commons.logging的依赖包。

    错误如下：

Reason: Missing Constraint: Import-Package: org.apache.commons.logging; version="[1.1.1,2.0.0)"

    经过仔细的对比和设置，最终发现需要加入以下的4个包，才能使spring-core启动起来（这四个包均位于spring dm2.0包的lib目录下）：

```
com.springsource.slf4j.org.apache.commons.logging-1.5.6.jar
com.springsource.slf4j.api-1.5.6.jar
com.springsource.slf4j.log4j-1.5.6.jar
com.springsource.org.apache.log4j-1.2.15.jar
```

 

    实际上，spring-core只需要使用commons.logging包，但在这里的commons-logging包又依赖于slf4j.api包，然后alf4j.api启动slf4j.log4j，最后由log4j实现包来实现日志的记录。

    详细查看相应的import和export可以发现其中的依赖关系详细如下：

```
org.springframework.core-3.0.0.RC1.jar->import:org.apache.commons.logging;version="[1.1.1, 2.0.0)"
com.springsource.slf4j.org.apache.commons.logging-1.5.6.jar->org.slf4j;version="[1.5.6, 1.5.6]",org.slf4j.spi;versi
 on="[1.5.6, 1.5.6]"
com.springsource.slf4j.api-1.5.6.jar->org.slf4j.impl;version="[1.5.6, 2.0.0)"
com.springsource.slf4j.log4j-1.5.6.jar->org.apache.log4j;version="[1.2.15, 2.0.0)"
com.springsource.org.apache.log4j-1.2.15.jar
```

 

    在其中，com.springsource.slf4j.log4j-1.5.6.jar并不是一个独立的bundle包，而是依附于com.springsource.slf4j.api-1.5.6.jar启动，这个可以由其中的Fragment-Host: com.springsource.slf4j.api;bundle-version="\[1.5.6, 1.5.6]"可以得出。

    值得注意的是，在这里，sprng-core中指定了相应的logging包的版本为[1.1.1,2.0.0)，所以，随便导入一个logging是不行的，并且相应的log4j也要遵循相应的版本要求。

    在使用了maven之后，我们的commons-logging可以从maven中进行导出，但是官方的commons-logging-1.1.1并没有osgi化，即在其中的manifest.mf文件并没有相应的bundle设置。我们可以用bnd插件来将它osgi化，即在相应的export-package中指定导出的版本为version="1.1.1"即可。如下：

```
Export-Package: org.apache.commons.logging;version="1.1.1"
```

这样就可以不再需要导入slf4j以及log4j包了。

    在intellij idea中，使用了OSGI插件即Osmorc，可以直接在相应的设置中指定bundle的参数，就可以在运行中将commons-loggin转化成bundle包了。如下：

![commons-logging bundle设置](http://dl.iteye.com/upload/attachment/256057/6c3604d4-6c88-3981-a268-a10d519c995b.jpg)

    这样，就完成了对commons-logging的使用，值得一提的就是，在pom.xml定义要引用的jar时，如果jar不是osgi-ready的，那么idea会进行提示，太好了。