以上所有答案都是正确的。现在要在 shell 上打印一些东西,你可以编写如下内容:
public interface PrintService {
public void print();
}
实施:
public class PrintServiceImpl implements PrintService {
@Override
public void print() {
System.out.println("Hello from PrintServiceImpl!");
}
}
组件.xml:
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="service">
<implementation class="service.PrintServiceImpl"/>
<service>
<provide interface="print.PrintService"/>
</service>
</scr:component>
现在您可以使用命令来调用您的打印方法:
public class PrintCommand implements Command {
private PrintService printer;
public void setPrinter(PrintService printer) {
this.printer = printer;
}
public void unsetPrinter(PrintService printer) {
this.printer = null;
}
@Override
public void execute(String line, PrintStream arg1, PrintStream arg2) {
printer.print();
}
@Override
public String getName() {
return "print";
}
@Override
public String getShortDescription() {
return "just a printer";
}
@Override
public String getUsage() {
return "print";
}
}
您的 component.xml 应该有一个新条目:
<component name="PrintCommand">
<implementation class="PrintCommand"/>
<service>
<provide interface="org.apache.felix.shell.Command"/>
</service>
<reference
name="printer"
interface="PrintService"
bind="setPrinter"
unbind="unsetPrinter"
cardinality="1..1"
policy="static"
/>
</component>
命令界面是 Apache Felix Shell 的一部分,如果您现在运行 Felix 并help
在控制台中输入,您将看到所有已注册的命令,并且还有 PrintCommand print
。如果您现在在 shell 中键入 print,您将看到文本。