如何在 OSGI Declarative Services Annotations 中使用 java 属性文件

How to use java properties file in OSGI Declarative Services Annotations

我正在尝试使用 bndtools 创建我的 OSGI 程序。这是我之前的代码,在felix console下可以正常运行。

package com.buaa.ate.service.data.command;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.apache.felix.service.command.CommandProcessor;
import com.buaa.ate.service.api.data.Publisher;

@Component(
        service=PublishCommand.class,
        property={
                CommandProcessor.COMMAND_SCOPE + ":String=example",
                CommandProcessor.COMMAND_FUNCTION + ":String=publish",  
        }
)
public class PublishCommand {

    private Publisher publishSvc;
    @Reference
    public void setPublisher(Publisher publishSvc) {
        this.publishSvc = publishSvc;
    }
    public void publish(String content) {
        publishSvc.start();
        long result = publishSvc.publish(content);
        System.out.println(result);
        publishSvc.stop();
    }
}

现在,我想像这样更改注释:

package com.buaa.ate.service.data.command;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.apache.felix.service.command.CommandProcessor;
import com.buaa.ate.service.api.data.Publisher;

@Component(
        service=PublishCommand.class,
        properties="com/buaa/ate/service/data/command/config.properties"
)
public class PublishCommand {

    private Publisher publishSvc;
    @Reference
    public void setPublisher(Publisher publishSvc) {
        this.publishSvc = publishSvc;
    }
    public void publish(String content) {
        publishSvc.start();
        long result = publishSvc.publish(content);
        System.out.println(result);
        publishSvc.stop();
    }
}

这是我的属性文件: config.properties

内容是这样的:

osgi.command.scope\:String:example
osgi.command.function\:String:publish

我在运行程序中,输入命令'publish something',出现问题:

'gogo: CommandNotFoundException: Command not found: publish'

那么,我应该怎么做才能解决这个问题?

好吧,我才发现解决这个问题很容易。这是 osgi javadoc 的一部分:

property

public abstract java.lang.String[] property

Properties for this Component. Each property string is specified as "key=value". The type of the property value can be specified in the key as key:type=value. The type must be one of the property types supported by the type attribute of the property element of a Component Description.

To specify a property with multiple values, use multiple key, value pairs. For example, "foo=bar", "foo=baz".

See Also: "The property element of a Component Description."

Default:{}

所以我把'type' 属性加到config.properties,然后代码就可以正常运行了。这是当前的属性文件: current properties file

它的内容是这样的:

osgi.command.scope=example
osgi.command.scope\:type:String
osgi.command.function=publish
osgi.command.function\:type:String

程序现在可以正常运行了。