2

I noticed multiple ways in which developers create an Apache Felix Service. Each of the attached snippets seem to work. Would need some help to understand, which syntax is best for which scenario

Sample 1: Service created without interface

  • Declaration of Service

D

@Component
@Service(ServiceViaClass.class)
public class ServiceViaClass{
}
  • Using service via @Reference annotation

    private ServiceViaClass serviceViaClass;

Sample 2:Service implementing interface. No value attribute for @Service annotation - Declaration of Service

@Component
@Service
public class ServiceViaInterfaceImpl implements ServiceViaInterface{
}
  • Using service via @Reference annotation

    private ServiceViaInterface serviceViaInterface;

Sample 3: Service implementing interface with value attribute for @Service annotation - Declaration of Service

@Component
@Service(ServiceViaInterface.class)
public class ServiceViaInterfaceImpl implements ServiceViaInterface{
}
  • Using service via @Reference annotation

    private ServiceViaInterface serviceViaInterface;

Puce
  • 37,247
  • 13
  • 80
  • 152

1 Answers1

1

A component implements an interface and publishes itself as a service under that interface, so that clients can find the component using only the interface.

Sample 1 — publishing a service using the concrete type of the component — is nearly always useless. The service can only be found using the concrete type, and if clients can see the concrete type then why not just instantiate it directly rather than get an instance from the service registry??

Sample 2 — publishing a service by implementing an interface and then just adding the @Service annotation — is what you should usually do. When you use @Service and the component directly implements an interface, the build tooling infers that your component wants to be published as a service under that interface.

Sample 3 has the exact same effect at runtime as sample 2, it's just a bit more explicit in the code. Some people prefer this because it's explicit, others (including me) dislike it because it is redundant.

Neil Bartlett
  • 23,743
  • 4
  • 44
  • 77