0

The project is set up with CDI 2.0 (specifically Weld 3.0.4). Now I want to have a service accessing and caching an external REST interface.

For the sake of simplicity let's assume this REST interface is returning Json objects for given numeric identifiers, speaking in Java: service.getProduct(int productKey).

What is the 'CDI way' to write such a service, specifically the scope and the instantiation of Product objects (which are returned by the service)?

(Incomplete) Pseudo code:

public class ProductService {
    public Product getProduct(int productKey) {
        String json = rest.get(productKey);
        return new Product(json);
    }
}

...

@Produces
public Product create(int productKey) {
    return new Product(productKey);
}

From my research producer methods do not support runtime parameters. So how to bring these two parts together?

towi
  • 11
  • 1

1 Answers1

0

First of all, it is a misconception, that each and every object in a CDI container has to be created via CDI. The CDI managed beans are usually services as opposed to simple data objects which do not need injection at all.

Thus, if your Product class does not have the need to interact with services, just use a normal factory which you can inject and use.

If you really need multiple instances of fully CDI capable Products, a common way is to move the actual parametrization to a separate method, e.g.

public class Product {
    // the reason to use CDI in Product:
    @Inject SomeService myService;

    // Normal "data object" properties
    private String productId;
    private String procuctName;

    public void init(...) {
       this.productId = ...
       this.productName = ...
    }
}

And in the caller:

@Inject Provider<Product> productFactory;

public Product getProduct(int productKey) {
    String json = rest.get(productKey);
    Product result = productFactory.get();
    result.init(json);
    return result;
}
mtj
  • 3,381
  • 19
  • 30