Reputation: 39
I have a class A
which is kind of a wrapper over class B
just to make B Serializable
. Now I have class C
in which I need to inject class A
to be instantiated with attributes 'a
' and 'b
'. How can this be achieved?
The following is my code:
Class A extends B {
public A(int a, int b){
super(a,b);
}
class C{
@Inject
A objA; //will not work
}
Upvotes: 0
Views: 68
Reputation: 690
I think I agree with maress in that you're probably doing something fundamentally wrong, but without your entire use case, I'll offer the following:
Your class A, as it stands, cannot be injected into C because it is not a CDI bean. In order to be a CDI bean, it must have either a no-arg constructor or a constructor annotated with @Inject.
In this case, even if you annotate your constructor with @Inject:
@Inject
public A(int a, int b) { ... }
You still will not be able to inject A into C. The problem is that there many ways to satisfy that constructor. The container will not know which ints you mean to inject. That is, did you want it to instantiate an A(0,0) or an A(1,2) or an A(-12, 5001) or ... ?
You have a few options. You can use a qualifier (such as @Named) to disambiguate the particular ints that you want to inject:
@Inject
public A(@Named("int1") int a, @Named("int2") int b) {...}
The qualified ints can be generated via a producer method:
@Produces @Named("int1")
public int get_int1() { return 5; }
@Produces @Named("int2")
public int get_int2() { return 6; }
Alternately, you could use a producer method to produce instances of your A:
@Produces
public A get_A() { return new A(5,6); }
Upvotes: 0
Reputation: 3533
Generally, its a good design practice not to pass data through constructor for injectable services. make your services as stateless and reusable as much as possible.
If that's not possible, you can check on CDI producer semantics here: Using producer methods and Fields
Upvotes: 1