Apache Sling Context Aware Configuration in AEM
Create Configuration Interface
configs / SiteConfig.java
public SiteConfig {
String contentPath();
String siteDomain();
String approverGroup();
}
Implement Configuration Service
services / impl / SiteConfigServiceImpl.java
public class SiteConfigServiceImpl implements SiteConfigService {
public SiteConfig getSiteConfig(Resource resource) {
ConfigurationBuilder configurationBuilder = resource.adaptTo(ConfigurationBuilder.class);
return configurationBuilder != null ? configurationBuilder.as(SiteConfig.class) : null;
}
}
Configure in /conf Directory
- Navigate to /conf/aem-demo/sling:configs
- Create a node with your configuration name: com.aem.demo.core.configs.SiteConfig
- Add the configuration properties as shown below:
/conf / aem-demo / sling:configs / com.aem.demo.core.configs.SiteConfig / .content.xml
<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:sling="http://sling.apache.org/jcr/sling/1.0"
xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
jcr:primaryType="nt:unstructured"
contentPath="/content/aem-demo"
siteDomain="http://local.aemdemo.com"
approverGroup="aem-demo-content-approver"/>
Connect Content with Configuration
/content / aem-demo / .content.xml
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:cq="http://www.day.com/jcr/cq/1.0"
xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
jcr:primaryType="cq:Page">
<jcr:content jcr:primaryType="cq:PageContent"
cq:conf="/conf/aem-demo"
cq:redirectTarget="/content/aem-demo/us/en"
cq:template="/conf/aem-demo/settings/wcm/templates/page-content"
jcr:title="AEM Demo"
sling:configRef="/conf/aem-demo"
sling:redirect="{Boolean}true"
sling:redirectStatus="{Long}302"
sling:resourceType="aem-demo/components/page"/>
</jcr:root>
Using Configuration in Components
components / internal / models / impl / PageConfigImpl.java
public class PageConfigImpl implements PageConfig {
private SiteConfigService configService;
protected Resource resource;
private SiteConfig config;
protected void init() {
this.config = configService.getSiteConfig(resource);
}
public String getContentPath() {
return config != null ? config.contentPath() : null;
}
public String getSiteDomain() {
return config != null ? config.siteDomain() : null;
}
}