Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.
SOLVED

How to acces annotation properties

Avatar

Level 4

Hi,

I have a property like this:

@Property(name = "myvar", value = "myvalue")

I need to access this property inside the code.

I can do this with:

@Activate public void activate(ComponentContext ctx) { Dictionary dic = ctx.getProperties(); Enumeration keys = dic.keys(); List<String> list = Collections.list(keys); Collections.sort(list); for (String key : list) if (key.equals("myvar")) portal_server = String.valueOf(dic.get((Object) key)); }

Is there a simpler way?

Thanks

1 Accepted Solution

Avatar

Correct answer by
Employee Advisor

Hi,

I use code like this:

@Activate protected void activate (ComponentContext ctx) { String myvar = PropertyUtils.toString (ctx.getProperties().get("myvar"), "defaultValue"); }

The PropertyUtils helper is very useful, as it provides many conversion tools including the support for a default value, if the property is not provided or empty.

View solution in original post

3 Replies

Avatar

Level 10

Invoking the https://osgi.org/javadoc/r4v42/org/osgi/service/component/ComponentContext.html#getProperties() method is the supported way to dynamically determine properties values used within OSGi. 

Avatar

Level 5

You can also do something like

@Activate protected void activate(final Map<String, Object> config) { String myvar = PropertiesUtil.toString(config.get(PROP_NAME),DEFAULT_VALUE); }

Avatar

Correct answer by
Employee Advisor

Hi,

I use code like this:

@Activate protected void activate (ComponentContext ctx) { String myvar = PropertyUtils.toString (ctx.getProperties().get("myvar"), "defaultValue"); }

The PropertyUtils helper is very useful, as it provides many conversion tools including the support for a default value, if the property is not provided or empty.