Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CDI constructor injection don't work with transient non-serializable dependencies

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?

like image 318
Manuel Mauky Avatar asked Nov 13 '22 11:11

Manuel Mauky


1 Answers

That seems like a bug. Does everything work well if you make BeanA serializable? Also which version of Weld are you using?

like image 112
LightGuard Avatar answered Nov 16 '22 02:11

LightGuard