CQ5-sling:Java类中的OsgiConfig服务

CQ5-sling:Java类中的OsgiConfig服务,java,osgi,aem,sling,Java,Osgi,Aem,Sling,我创建了一个sling:OsgiConfig节点,它的属性路径类型为String[]。我需要在java类中访问此属性。我想在java类中创建一个从JSP调用的方法。我正在使用taglib进行此操作。我知道我们可以使用下面的代码在JSP中实现同样的功能: Configuration conf = sling.getService(org.osgi.service.cm.ConfigurationAdmin.class).getConfiguration("Name of the confi

我创建了一个sling:OsgiConfig节点,它的属性路径类型为String[]。我需要在java类中访问此属性。我想在java类中创建一个从JSP调用的方法。我正在使用taglib进行此操作。我知道我们可以使用下面的代码在JSP中实现同样的功能:

    Configuration conf = sling.getService(org.osgi.service.cm.ConfigurationAdmin.class).getConfiguration("Name of the config");
String[] myProp = (String[]) conf.getProperties().get("propertyPath");

如何在Java类中执行此操作。

您需要在服务的activate方法中使用该代码。您可以使用注释将类标识为服务

@Component(label = "Title", description = "Description.", immediate = true, metatype = true, policy = ConfigurationPolicy.REQUIRE)
@Service(value = {YourServiceInterface.class})
@Properties({
    @Property(name = "propertyPath", label = "Property Label", description = "Property Desc.")
})
然后您可以定义一个activate方法来将它们拉出

protected void activate(ComponentContext context) throws RepositoryException {
    String[] myProp = (String[])context.getProperties().get("propertyPath");
    // or
    String[] myProp = PropertiesUtil.toStringArray(context.getProperties().get("propertyPath"));
}

您没有说您希望在哪种类型的Java类中获得配置。让我们看一下选项:

1。任何OSGi服务(如servlet、过滤器或事件侦听器)

将以下字段添加到OSGi组件类:

@Reference
private ConfigurationAdmin configurationAdmin;
并以与JSP中相同的方式使用它

2。sling:OsgiConfig所属的OSGi服务

如果您添加了
sling:OsgiConfig
节点来配置自己的OSGi组件,请遵循Chris的建议:

@Component
@Properties({
    @Property(name = "propertyPath")
})
public class MyComponent {

    private String[] propertyPath;

    @Activate
    public void activate(ComponentContext ctx) {
        propertyPath = PropertiesUtil.toStringArray(context.getProperties().get("propertyPath"));
    }

    public void myMethod() {
        // do something with the propertyPath field
    }
}
activate方法由OSGi自动调用。
ComponentContext
的限定名称为

3。普通旧Java对象

如果您的类不是OSGi组件,那么您至少需要有权访问
SlingHttpServletRequest
对象。如果这样做,您可以从中提取
SlingScriptHelper
,并使用它获取
ConfigurationAdmin

SlingHttpServletRequest request = ...;
SlingBindings bindings = (SlingBindings) request.getAttribute(SlingBindings.class.getName());
SlingScriptHelper sling = bindings.getSling();
// here you can use your JSP code

谢谢你的回复,克里斯。请告诉我此ComponentContext是否属于com.day.cq.wcm.api.components。因为我在这个ComponentContext中找不到getProperties()方法。此外,一旦我有了propertyPath的值,我如何在其他方法中获取该值。我必须调用激活方法吗?我相信这是您需要的导入。导入org.osgi.service.component.ComponentContext;