Setting properties in Adobe CQ5

Kostya picture Kostya · Jan 17, 2013 · Viewed 9.7k times · Source

I'm working on CQ5 based app, which is a whole new area for me as I was mainly working on Spring based web-apps before.

The app is maven project based on Blue-prints archetype(http://www.cqblueprints.com/xwiki/bin/view/Blue+Prints/The+CQ+Project+Maven+Archetype).

Now I have a question, what is a standard approach to add some properties, that would normally go to config.properties (or alike) file in standard web-app. Properties that contain things like hostNames, accountNumbers and alike.

Cheers.

Answer

Bertrand Delacretaz picture Bertrand Delacretaz · Jan 17, 2013

I'm not familiar with blueprints, but as I understand that's just a way to generate your CQ project structure, so I assume it doesn't have any real impact on how you manage configuration parameters.

CQ5 is based on Apache Sling, which uses the OSGi ConfigAdmin service for configurable parameters, and provides a few tools to make this easier.

You can see an example of that in the PathBasedDecorator Sling component, which uses the @Component annotation to declare itself as an OSGi component:

@Component(metatype=true, ...)

and later uses an @Property annotation to declare a multi-value configurable parameter, with default values:

@Property(value={"/content:2", "/sling-test-pbrt:2"}, unbounded=PropertyUnbounded.ARRAY)
private static final String PROP_PATH_MAPPING = "path.mapping";

That value is then read in the component's activate() method:

  final Dictionary<?, ?> properties = componentContext.getProperties();
  final String[] mappingList = (String[]) properties.get(PROP_PATH_MAPPING);

and the OSGi bundle that contains that component provides a metatype.properties file to define the name and label of the configurable parameter.

That's it - with this, Sling and the OSGi framework generate a basic config UI for the component, that you can access from /system/console/config, and manage your component's activation and reactivation automatically if configuration parameters change.

Those configurations can also come from the JCR repository, thanks to the Sling installer which picks them up there, you can find a number of those in folders named "config" under /libs and /apps in your CQ5 repository.

Another option is to use JCR content directly, depending on how your configurable parameters are used. You could tell your component that its config is under /apps/foo/myparameters in the repository (and make just that value configurable), and add JCR properties and child nodes under that node as needed, that your component can read. The disadvantage is that your @Component won't be restarted automatically when parameters change, as happens when using OSGi configurations directly.

Long explanation...hope this helps ;-)