OSGi服务

了解OSGi服务开发的基础知识,包括:

  • 如何将Java POJO转换为OSGi服务
  • 如何将OSGi服务绑定到Java接口

资源

代码

Activities.java

/core/src/main/java/com/adobe/aem/wknd/examples/core/adventures/Activities.java

package com.adobe.aem.wknd.examples.core.adventures;

import org.osgi.annotation.versioning.ProviderType;

@ProviderType
public interface Activities {
    String getRandomActivity();
}

ActivitiesImpl.java

/core/src/main/java/com/adobe/aem/wknd/examples/core/adventures/impl/ActivitiesImpl.java

package com.adobe.aem.wknd.examples.core.adventures.impl;

import java.util.Random;

import com.adobe.aem.wknd.examples.core.adventures.Activities;

import org.osgi.service.component.annotations.Component;

@Component(
    service = { Activities.class }
)
public class ActivitiesImpl implements Activities {

    private static final String[] ACTIVITIES = new String[] {
        "Camping", "Skiing",  "Skateboarding"
    };

    //private final int randomIndex = new Random().nextInt(ACTIVITIES.length);
    private final Random random = new Random();

    /**
     * @return the name of a random WKND adventure activity
     */
    public String getRandomActivity() {
        int randomIndex = random.nextInt(ACTIVITIES.length);
        return ACTIVITIES[randomIndex];
    }
}

package-info.java

/core/src/main/java/com/adobe/aem/wknd/examples/core/adventures/package-info.java

@Version("1.0")
package com.adobe.aem.wknd.examples.core.adventures;

import org.osgi.annotation.versioning.Version;

需要添加package-info.java,以确保AEM中的其他OSGi捆绑包能够解析OSGi服务接口(或任何Java类)。 如果package-info.java缺失,则不会导出Java包及其Java接口或类。 尝试从此Java包导入这些Java接口或类的其他OSGi包将出错,并出现消息​无法解析 AEM的OSGi包控制台。

recommendation-more-help
4859a77c-7971-4ac9-8f5c-4260823c6f69