Annotation Type Service


  • @Documented
    @Retention(RUNTIME)
    @Target({TYPE,ANNOTATION_TYPE})
    public @interface Service
    A service is a stateless object that implements domain, applicative, infrastructure or interface logic.

    This annotation can be applied to an interface to declare a service. Any class implementing the annotated interface will be registered by the framework as an implementation of this service.

    Considering the following service:

     @Service
      public interface MoneyTransferService {
         void transfer(Account source, Account target);
      }
     
    Its implementation is declared as:
      public class ElectronicMoneyTransferService implements MoneyTransferService {
          public void transfer(Account source, Account target) {
              // implementation
          }
      }
     
    The implementation can then be injected as follows:
     public class SomeClass {
         @Inject
          MoneyTransferService moneyTransferService;
     }
     

    When a service interface has multiple implementations, it is necessary to differentiate them by using a different javax.inject.Qualifier annotation on each. This qualifier can then be used at the injection point to specify which implementation is required. Considering the additional implementation of the MoneyTransferService below:

     @Named("solidGold")
      public class SolidGoldMoneyTransferService implements MoneyTransferService {
          public void transfer(Account source, Account target) {
              // implementation
          }
      }
     

    This implementation can be injected as follows:

      public class SomeClass {
          @Inject
          @Named("solidGold")
           TransferService transferService;
      }