Java – CDI constructor injection is not applicable to transient non serializable dependencies

I like CDI's constructor injection, but now I've found a use case where constructor injection obviously doesn't work as expected

In my example, I have two classes Class "beana" has no well-defined scope and does not implement serializable Class "beanb" annotates with @ sessionscope and implements 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 a bean, I get an serializabledependencyexception from weld because beana is not serializable This is expected behavior

When I mark the "beana" field with "transient", there is no problem with the injection:

@Inject
private transient BeanA beanA;

Now weld will not throw any exceptions

This is very good for me, but when I like to use constructor injection, my understanding problems arise It no longer works when I do the following:

@SessionScoped
public class BeanB implements Serializable{
    private transient BeanA beanA;

    @Inject
    public BeanB(BeanA beanA){
        this.beanA = beanA;
    }

    public BeanB(){}
}

Using this code, I get unserializabledependencyexception again I think constructor injection and field injection are more or less equal, but obviously they are not What's my fault?

Solution

This seems to be a mistake If you make beana serializable, does everything work well? Which version of weld do you still use?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>