Header image for article "migration to OSGi annotations caveats"

OSGi: migration to OSGi annotations caveats

I think that every developer from AEM/Sling world has already read many articles regarding switching to the R6 and R7 OSGi annotations. But new annotations do not only allow us to write less boilerplate code, but also bring new caveats and we better be aware of them.

Several days ago there was suggested a PR for AC Tool which fixes missing referenced service in AEM 6.4, even though this service was shown as satisfied in Web Console. The fix contained next change:

Konrad Windszus identified that this issue was the result of switching to the official OSGi annotations in AC Tool. This switch changed method injection to field injection and OSGi R7 Specification in 112.3.9.1 states next:

For a dynamic reference, the field must be declared with the volatile modifier so that field value changes made by SCR are visible to other threads. If the field is not declared with the volatile modifier, SCR must log an error message with the Log Service, if present, and the field must not be modified.

This perfectly describes why the field was not initialized. But this is not the only problem you may hit while switching to OSGi annotations – there are 2 more related excerpts worth mentioning:

If the field is declared with the final modifier, SCR must log an error message with the Log Service, if present, and the field must not be modified.

For a reference with multiple cardinality, the type of the field must be Collection or List. If the field has a different type, SCR must log an error message with the Log Service, if present, and the field must not be modified.

How to survive?

Luckily for us, next release (4.2.0) of Bnd (including bnd-maven-plugin) will contain corresponding checks, so we will be notified about such problems at early stage – during the build.

This is another example which proves that reading specification is not a waste of time but a way to prevent such issues from happening.

So don’t forget to read specifications as well as update your dependencies as soon as 4.2.0 is released.

Your thoughts are welcome