非序列化注入bean的序列化过程,关键字为“瞬态”

时间:2017-05-31 12:19:41

标签: java serialization cdi

我在java中遇到序列化问题。

以下是测试用例类TestLoggerBean

import org.apache.commons.logging.Log;

import javax.inject.Inject;
import java.io.Serializable;


public final class TestLoggerBean implements Serializable{
    private static final long serialVersionUID = 1L;

    @Inject
    protected transient Log logger;

    @Inject
    protected Log logger2;

    public void showMessage() {
        this.logger.info( "Logger 1" );
    }

    public void showMessage2() {
        this.logger2.info( "Logger 2" );
    }
}

识别TestClass:

public class TestClass implements Serializable {
    private static final long   serialVersionUID    = 1L;


    @Inject
    private TestLoggerBean testLoggerBean;

    public void testSerial() {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out = null;

        byte[] yourBytes = null;
        try {
            out = new ObjectOutputStream(bos);
            out.writeObject( this.testLoggerBean );
            out.flush();
            yourBytes = bos.toByteArray();
        } catch (IOException ex) {
            // ignore close exception
        } finally {
            try {
                bos.close();
            } catch (IOException ex) {
                // ignore close exception
            }
        }

        ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
        ObjectInput in = null;
        TestLoggerBean o = null;
        try {
            in = new ObjectInputStream(bis);
            o = (TestLoggerBean) in.readObject();
        } catch (IOException ex) {
            // ignore close exception
        } catch ( ClassNotFoundException e ) {
            e.printStackTrace();
        } finally {
            try {
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            // ignore close exception
        }

        o.showMessage2();

        o.showMessage();
    }
}

见截图:

Screen1

向上:序列化前的对象;

向下:序列化后的对象

我们可以看到瞬态字段为null(向上)。 非瞬态字段似乎在序列化后重新注入对象。对于我的应用程序,非瞬态字段的行为很好。请参见示例函数showMessage2。瞬态字段将在方法NullPointerException中生成showMessage()

现在我有以下问题。在我的项目中,对象的序列化非常重要,我很高兴每个有助于检测序列化问题的功能。我的IDE(Intellij)显示非瞬态字段: Screen2。根据我的测试结果,我无法使用关键字“瞬态”,我的应用程序无法正常工作。没有关键字'transient'应用程序可以正常工作,但我无法使用代码分析功能。

我的问题。我的测试用例中是否遗漏了一些常见内容?处理这些情况的最佳方法是什么?测试中的两个选项都不适用于我。

2 个答案:

答案 0 :(得分:0)

您可以使记录器静态最终,并避免使用注释answer here注入记录器

答案 1 :(得分:0)

transient关键字与CDI结合使用意味着只有在首次实例化此类对象时才会注入此类字段。例如。第一次创建时。

如果在此之后的任何时间,物体需要被塞进/灭绝transient字段将不会被重新注入(而其他字段将是 - 那是什么你观察其他领域)。

如果你销毁这样的bean并重新实例化它(例如会话bean到期),那么transient字段将再次注入,直到第一次序列化。