CDI 构造函数注入不适用于瞬态不可序列化依赖项

Man*_*uky 5 java serializable transient constructor-injection cdi

我非常喜欢 CDI 的构造函数注入,但现在我发现了一个用例,其中构造函数注入显然无法按预期工作。

在我的示例中,我有两个类。类“BeanA”没有明确定义的范围,也没有实现可序列化。类“BeanB”使用@SessionScoped 进行注释并且确实实现了可序列化。

public class BeanA{
}

@SessionScoped
public class BeanB implements Serializable{
    @Inject
    private BeanA beanA;
}
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

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(){}
}
Run Code Online (Sandbox Code Playgroud)

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?

Lig*_*ard 2

这似乎是一个错误。如果使 BeanA 可序列化,一切都会正常吗?另外您使用的是哪个版本的 Weld?