I am trying to inject an instance of a CDI managed bean with constructor parameters. I have annotated a constructor that takes parameters with @Inject, for example :-
@Stateless
public class ShoppingCart {
int capacity;
ShoppingCart(){};
@Inject
ShoppingCart(int capacity) {
this.capacity = capacity;
}
'
'
}
How can I inject a shoppingCart instance into another CDI managed bean so that I actually have a ShoppingCart instance I can call other methods on? equivalent to :-
ShoppingCart sc = new ShoppingCart(10);
All the examples seem to just access properties in the referenced bean and don't actually obtain an instance of the bean itself, e.g. from 3.7. Bean constructors
@SessionScoped
public class ShoppingCart implements Serializable {
private User customer;
@Inject
public ShoppingCart(User customer) {
this.customer = customer;
}
public ShoppingCart(ShoppingCart original) {
this.customer = original.customer;
}
ShoppingCart() {}
...
}
@ConversationScoped
public class Order {
private Product product;
private User customer;
@Inject
public Order(@Selected Product product, User customer) {
this.product = product;
this.customer = customer;
}
public Order(Order original) {
this.product = original.product;
this.customer = original.customer;
}
Order() {}
...
}
The Order instance does not end up with a ShoppingCart object on which it could call ShoppingCart methods which you would end up with if you did
@Inject
ShoppingCart cart;
but of course this then requires you to use a setter method to pass in the capacity value afterwards with a setter method :-
cart.setCapacity = 10;
There seems some doubt in my mind if it's actually possible to @Inject a bean with constructor parameters? I haven't found an example yet, any help always appreciated.