I like the constructor injection of CDI a lot but now I found a usecase where constructor injection apparently doesn't work as expected.
In my example I have two classes. Class "BeanA" has no explicit scope defined and does not implement Serializable. Class "BeanB" is annotated with @SessionScoped and does implement Serializable.
public class BeanA{
}
@SessionScoped
public class BeanB implements Serializable{
@Inject
private BeanA beanA;
}
When I try to inject an instance of BeanA into BeanB of cource I get an UnserializableDependencyException from Weld because BeanA isn't serializable. This is the expected behaviour.
When I mark the field "beanA" with "transient" the injection works without problems:
@Inject
private transient BeanA beanA;
Now Weld doesn't throw any exceptions.
This is perfectly fine for me but my understanding problem comes when I like to get this working with constructor injection. When I do the following it doesn't work anymore:
@SessionScoped
public class BeanB implements Serializable{
private transient BeanA beanA;
@Inject
public BeanB(BeanA beanA){
this.beanA = beanA;
}
public BeanB(){}
}
With this code I get the UnserializableDependencyException again. I thought that constructor injection and field injection are more or less equivalent but obviously they aren't. What is my mistake?