Search code examples
osgiaemapache-felix

@Properties in OSGi


I was writting one service and observed @Property we can define also inside the service as in my below code :

@Component(metatype = true, immediate = true, description = "Demo Service to test")
@Service(value = DemoService.class)
@Properties({
        @Property(name = "testprop" , value = "This is Test Property")
})
public class DemoServiceImpl implements DemoService {
     @Property(name = "localprop", value = "Local Value")
    @Activate
    public void activate(ComponentContext ctx)
    {
        String testprop = (String)ctx.getProperties().get("testprop");
        String localprop = (String)ctx.getProperties().get("localprop");
    }
}

Both properties display in felix console & accessible inside my service. So what creates the difference to declare them inside component or outside. One i saw we can not use @Properties inside component. But not sure what makes them functionally different from each other & when to use each.


Solution

  • I guess you talk about the felix annotations.

    You can use @Property in front of any method or member variable. However, that does not mean that the method would be called or the variable would be set. The only good thing in it is that if you have a specific variable that will hold the value of the property (by assigning it in the activate method), your class can be more self explaining based on the annotations.

    In the other hand, you can list properties within the @Properties annotation. I prefer this way as in this case I can define exactly the order of properties how they should appear in the generated metatype xml file (and on the webconsole).

    It can also happen, that the configuration property is not assigned to any member variable, it is used only in the activate method. In that case the best place to define it is within the @Properties annotation in front of the class.