AEM 6.3及更高版本支持.cfg.json配置文件。以下是一个示例代码,演示如何在AEM中使用.cfg.json文件进行配置:
创建一个Osgi配置文件,命名为"myconfig.config",并将其放置在src/main/resources/META-INF/vault/config文件夹下。
在myconfig.config文件中添加所需的配置属性,如下所示:
# Sample configuration properties
my.property1=value1
my.property2=value2
package com.example.myproject;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.metatype.annotations.Designate;
@Component(service = ConfigService.class, immediate = true)
@Designate(ocd = MyConfig.class)
public class ConfigService {
private MyConfig config;
public String getProperty1() {
return config.my_property1();
}
public String getProperty2() {
return config.my_property2();
}
}
package com.example.myproject;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
@ObjectClassDefinition(name = "My Config")
public @interface MyConfig {
@AttributeDefinition(name = "Property 1")
String my_property1() default "default_value1";
@AttributeDefinition(name = "Property 2")
String my_property2() default "default_value2";
}
package com.example.myproject;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
@Component(service = MyComponent.class, immediate = true)
public class MyComponent {
@Reference
private ConfigService configService;
public void doSomething(SlingHttpServletRequest request) {
ResourceResolver resolver = request.getResourceResolver();
Resource resource = resolver.getResource("/path/to/resource");
String property1 = configService.getProperty1();
String property2 = configService.getProperty2();
// 使用配置属性进行处理
// ...
}
}
通过以上步骤,在AEM中可以使用.cfg.json配置文件创建和管理配置属性,并通过注入ConfigService来获取属性值。