Once you have the application configured so that administrators can configure it in System Settings, you might be wondering how to read the configuration from your application’s Java code.
The answer is that there are several ways. Which one you use depends on the context from which the configuration must be read:
-
From any Component class
-
From an MVC portlet’s JSP
-
From an MVC portlet’s Portlet class
-
From a non-Component class
This tutorial shows the first usage, reading the configuration from a Component class.
Reading Configurations from a Component Class
-
First set the
configurationPid
Component property as the fully qualified class name of the configuration class:@Component(configurationPid = "com.liferay.dynamic.data.mapping.form.web.configuration.DDMFormWebConfiguration")
-
Then provide an
activate
method, annotated with@Activate
to ensure the method is invoked as soon as the Component is started, and@Modified
so it’s invoked whenever the configuration is modified.@Activate @Modified protected void activate(Map<String, Object> properties) { _formWebConfiguration = ConfigurableUtil.createConfigurable( DDMFormWebConfiguration.class, properties); } private volatile DDMFormWebConfiguration _formWebConfiguration;
The
activate()
method calls the methodConfigurableUtil.createConfigurable()
to convert a map of the configuration’s properties to a typed class, which is easier to handle. The configuration is stored in avolatile
field. Don’t forget to make itvolatile
to prevent thread safety problems. -
Once the activate method is set up, retrieve particular properties from the configuration wherever they’re needed:
public void orderCar(String model) { order("car", model, _configuration.favoriteColor); }
This is dummy code: don’t try to find it in the Liferay source code. The String configuration value of
favoriteColor
is passed to theorder
method call, presumably so that whatever model car is ordered will be ordered in the configured favorite color.
With very few lines of code, you have a configurable application that dynamically changes its configuration, has an auto-generated UI, and uses a simple API to access the configuration.