Del*_*ung 3 java osgi maven apache-felix sling
我是一个完整的新手,所以我提前道歉.我正在尝试创建一个OSGi组件,它只显示一个hello world消息,并且可以通过felix的输入进行配置.然后在jsp页面上吐出来.我正在使用scr注释来帮助完成此操作.这是我的java代码
package com.training.cq5.trainingApp;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.osgi.service.component.ComponentContext;
import org.apache.sling.commons.osgi.PropertiesUtil;
@Component(label= "Welcome Message",
description = "Welcome Message for the training excercise",
immediate = true, enabled = true, metatype=true)
@Properties({
@Property(name = "welcome.message", value = "WelcomeMessage")
})
@Service(WelcomeMessage.class)
public class WelcomeMessage {
private static String welcome_message = "Welcome";
@Activate
protected void activate(ComponentContext ctx) {
welcome_message = PropertiesUtil.toString(ctx.getProperties().get(welcome_message), welcome_message);
}
public static String getMessage() {
return welcome_message;
}
}
Run Code Online (Sandbox Code Playgroud)
以下是我在JSP中调用它:
<%@ page import="com.training.cq5.trainingApp.WelcomeMessage" %>
<h2><%= WelcomeMessage.getMessage() %></h2>
Run Code Online (Sandbox Code Playgroud)
有没有理由说它没有从felix更新?我得到的只是来自welcome_message字符串的"欢迎"文本.
您正在访问WelcomeMessage.getMessage()作为静态方法,但您想要的是实际服务.当你注释与@Service和@Component注解类,你指示,你想这个类注册为一个服务实例的OSGi框架.此服务实例由OSGI框架管理,在其生命周期(实例化时)或通过类加载器加载适当的类.
但是,为了使用@Component和@Service注释,您必须使用Apache Felix SCR插件.一旦有效,您的服务将被实例化.
然后你将不得不访问该服务.您似乎正在使用的Sling中最简单的方法是SlingScriptHelper.getService(),它允许您查找服务.
更新
在OSGI中,服务按其类型注册.当您使用@Service(MyClass.class)声明服务时,该服务将在MyClass类型下注册.要检索它,您将在服务注册表中查询给定类型的服务.在Java代码中,您将使用getServiceReference(Class clazz)/getService(ServiceReference引用)和@Reference注释.
在Sling系统上的JSP中,您可以使用SlingScriptHelper,如前所述.这是一个简短的代码示例(假设正确的导入):
<%
SlingBindings bindings = (SlingBindings) req.getAttribute(SlingBindings.class.getName());
SlingScriptHelper scriptHelper = bindings.getSling();
MyService service = scriptHelper.getService(MyService.class);
// ... do stuff with service.
%>
Run Code Online (Sandbox Code Playgroud)
如果您打算更多地使用OSGI,我强烈推荐OSGI规范.它可以免费下载并详细解释所有内容.
| 归档时间: |
|
| 查看次数: |
5368 次 |
| 最近记录: |