亲爱的天才程序员!我一直在使用 OSGI 框架,并试图在我的程序中应用声明式服务,但它在屏幕上什么也没打印。我的程序很简单,只有一个接口,一个类实现它,一个类作为客户端使用接口。
- 界面是:
package test.osdids.date;
public interface IDateService {
String getDate();
}
- 该类实现接口,因为服务是:
package test.osdids.date.service;
import java.util.Calendar;
import test.osdids.date.IDateService;
public class DateService implements IDateService {
@Override
public String getDate() {
String date = Calendar.getInstance().getTime().toString();
return date;
}
}
注册服务的 XML 是:
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0"
name="test.osdids.date.service">
<implementation class="test.osdids.date.service.DateService" />
<service>
<provide interface="test.osdids.date.IDateService" />
</service>
</scr:component>
该服务的清单文件是:
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: TESTOSDIDSDATESERVICE
Bundle-SymbolicName: TESTOSDIDSDATESERVICE
Bundle-Version: 1.0.0.qualifier
Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Service-Component: OSGI-INF/DateBridge.xml
Export-Package: test.osdids.date
Bundle-ActivationPolicy: lazy
- 现在,这是作为客户端使用服务并打印结果的类(该类位于其他插件项目中,与之前存储接口和实现类的插件项目不同) ):
package test.osdids.date.consumer;
import test.osdids.date.IDateService;
public class DateConsumer {
private IDateService dateService;
public synchronized void setService(IDateService dateService) {
this.dateService = dateService;
System.out
.println("The Date Service has been registered successfully!");
System.out.println("The current time is: " + dateService.getDate());
}
public synchronized void unsetService(IDateService dateService) {
System.out
.println("The Date Service has been unregistered successfully!");
}
public void activate() {
System.out.println("Test again...");
System.out.println("The current time is: " + dateService.getDate());
}
public void deactivate() {
System.out.println("Stop the service!");
}
}
- 这是消费和绑定消费者类服务的XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0"
name="test.osdids.date.consumer" activate="activate"
deactivate="deactivate" enabled="true" immediate="true">
<implementation class="test.osdids.date.consumer.DateConsumer" />
<reference bind="setService" cardinality="1..1"
interface="test.osdids.date.IDateService" name="IDateService" policy="static"
unbind="unsetService" />
</scr:component>
- 这是清单文件:
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: TESTOSDIDSDATECONSUMER
Bundle-SymbolicName: TESTOSDIDSDATECONSUMER
Bundle-Version: 1.0.0.qualifier
Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Require-Bundle: TESTOSDIDSDATESERVICE;bundle-version="1.0.0"
Service-Component: OSGI-INF/DateBridgeConsumer.xml
Import-Package: test.osdids.date
Bundle-ActivationPolicy: lazy
- 这是屏幕上的结果:
osgi>
(没啥事儿)
- 但是当我使用 jUnit 测试来测试 DateConsumer 类中的方法 activate() 时,它起作用了。但是,当我尝试通过 OSGI 框架运行插件项目时,什么也没有发生。
我希望有人知道这个问题并帮助我。提前非常感谢!