Reputation: 175
Assume i have Class A,B,C where Class B contains setters and getters. I want to use Class B in Class A(Perform Setter operation on Class B by setting true) and in Class C(Perform getter operation on Class B). But the issue iam facing is if the perform a get on the same Class B object true should get printed in Class C instead false is getting printed. The snippet is as below
Class A {
@Inject
B b;
//Setting true
b.set(true);
}
Class B {
boolean b;
//Setter
//Getter
}
Class C {
@Inject
B b;
//
boolean ball=b.get();
Log.info(ball) //False is getting printed instead of true why is this!!
}
Upvotes: 2
Views: 116
Reputation: 6753
The problem is, you are not giving your beans a scope - therefore by default they will all be @Dependent
. That is fine under some circumstances, but injecting a @Dependent
bean into another such beans will create a new instance.
In another words, class B
you inject into Class A
does not equals the one you inject into class C
.
Now, how to solve this?
For instance you could make the class B
an @ApplicationScoped
bean. The application scope lasts from CDi container boot (=from start) until the end. That way there will be one instance in the whole application and the state of the bean will therefore be shared amongst all the places you inject it into.
@ApplicationScoped
Class B {
boolean b;
//Setter
//Getter
}
Just a side note: Another answer here suggests using @Singleton
. I would advise against it, especially if you are in EE environment.
Upvotes: 2