CQ5 - sling:Java类中的OsgiConfig服务

use*_*418 2 java osgi sling aem

我创建了一个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");
Run Code Online (Sandbox Code Playgroud)

我怎样才能在Java类中执行此操作.

Tom*_*wek 6

您没有说过您希望获得哪种类型的Java类配置.我们来看看选项:

1.任何OSGi服务(如servlet,过滤器或事件监听器)

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

@Reference
private ConfigurationAdmin configurationAdmin;
Run Code Online (Sandbox Code Playgroud)

并以与JSP中相同的方式使用它.

2.吊索: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
    }
}
Run Code Online (Sandbox Code Playgroud)

OSGi自动调用activate方法.合格的名称ComponentContextorg.osgi.service.component.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
Run Code Online (Sandbox Code Playgroud)