/java/

Using @Specialization Annotation

2015-07-05 09:56:58

Let's assume that we have shop service:

package pl.btbw;

public class ShopService {

    // business logic

    public String getName() {
        return "ShopService";
    }
}

and we use this class in many place like this:

package pl.btbw;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/")
public class App {

    @Inject
    private ShopService shopService;

    @GET
    public String showCarName() {
        return shopService.getName();
    }

}

now "shopService.getName()" method return "ShopService"

If we want to override all behaviors for ShopService, but we don't want to touch ShopService or replease place where we use that class. We can use @Specializes annotation.

How it works ?

We have to create new class that extend ShopService and annotate this new class by @Specializes:

package pl.btbw;

import javax.enterprise.inject.Specializes;

@Specializes
public class SuperShopService extends ShopService {

    // @Override business logic

    @Override
    public String getName() {
        return "Super: " + super.getName();
    }
}

that it, now "shopService.getName()" method will return "Super: ShopService"

Github