OSGi配置作为ObjectClassDefinition对象
了解如何在OSGi服务中创建并指定ObjectClassDefinitions作为OSGi配置表示形式。
资源
代码
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.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(
service = { Activities.class }
)
@Designate(ocd = ActivitiesImpl.Config.class)
public class ActivitiesImpl implements Activities {
private static final Logger log = LoggerFactory.getLogger(ActivitiesImpl.class);
@ObjectClassDefinition(
name = "WKND Examples - Activities Service",
description = "OSGi Service providing information about WKND Adventures activities"
)
@interface Config {
@AttributeDefinition(
name = "WKND Activities",
description = "Human-friendly list of activity names"
)
String[] activities() default { "Hiking", "Jogging", "Walking" };
@AttributeDefinition(
name = "Random Activity Seed",
description = "Seed used to randomize activity selection"
)
int random_seed() default 10;
}
private String[] activities;
private Random random;
/**
* @return the name of a random WKND adventure activity
*/
public String getRandomActivity() {
int randomIndex = random.nextInt(activities.length);
return activities[randomIndex];
}
@Activate
protected void activate(Config config) {
this.activities = config.activities();
final int randomSeed = config.random_seed();
this.random = new Random(randomSeed);
log.info("Activated ActivitiesImpl with activities [ {} ]", String.join(", ", this.activities));
}
@Deactivate
protected void deactivate() {
log.info("ActivitiesImpl has been deactivated!");
}
}
com.adobe.aem.wknd.examples.core.adventures.impl.ActivitiesImpl.cfg.json
/ui.config/src/main/content/jcr_root/apps/wknd-examples/osgiconfig/config/com.adobe.aem.wknd.examples.core.adventures.impl.ActivitiesImpl.cfg.json
{
"random.seed:Integer":12,
"activities":[
"Skateboarding",
"Mountain Biking"
]
}
recommendation-more-help
4859a77c-7971-4ac9-8f5c-4260823c6f69