AEM 6.2如何访问使用servlet本身定义的OSGI配置

时间:2017-12-20 11:32:47

标签: aem

我创建了一个AEM servlet。现在我已经创建了OSGi配置(MULTI_FIELD,如下所示类型数组)with-in servlet本身,因为它也被定义为服务。现在,我的要求是如何在doGet方法中访问此osgi配置。这是servlet的代码。

@Component(label = "Sample Servlet", description = "Sample Servlet", immediate = true, metatype = true)
@Service
@Properties(value = {
    @Property(name = "sling.servlet.resourceTypes", value = { 
    GlobalConstants.RES_TYPE,
            GlobalConstants.PAGE_RES_TYPE }, propertyPrivate = 
 true),
    @Property(name = "sling.servlet.selectors", value = { 
 GlobalConstants.PAGES,
            GlobalConstants.ASSETS }, propertyPrivate = true),
    @Property(name = "sling.servlet.extensions", value = "xml", 
 propertyPrivate = true),

    @Property(name = "sling.servlet.methods", value = { "GET" }) })

public class SampleServlet extends SlingAllMethodsServlet {


 @Property(value={"English", "Hindi"}, unbounded = 
 PropertyUnbounded.ARRAY, label = "Subjects", cardinality = 50, 
 description = "Example for Multi field config") 
 private static final String MULTI_FIELD = "multifield";

    @Override
protected void doGet(final SlingHttpServletRequest request, final 
SlingHttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

}

2 个答案:

答案 0 :(得分:0)

您需要在激活方法中将属性值设置为成员字段:

@Activate
protected void activate(final BundleContext bundleContext, 
                        final Map<String, Object> componentConfig) {
   this.multiField = (String[]) componentConfig.get(MULTI_FIELD);
}

我自己没有尝试过代码,但它可以提供一些想法。您可以在此处查看Sling Main Servlet以查看其工作原理:http://svn.apache.org/repos/asf/sling/tags/org.apache.sling.engine-2.2.6/src/main/java/org/apache/sling/engine/impl/SlingMainServlet.java

答案 1 :(得分:0)

我同意Emin这应该在激活方法中处理。但是在6.2上,覆盖的方法只有一个参数,我会使用PropertiesUtil而不是强制转换。

该方法如下:

    @Activate
    public void activate(final ComponentContext componentContext) {
        final Dictionary<?, ?> props = componentContext.getProperties();
        this.multiField = Arrays.asList(PropertiesUtil.toStringArray(props.get(MULTI_FIELD), new String[0]));
    }