簡體   English   中英

關鍵字為“ transient”的不可序列化注入bean的序列化過程

[英]serialization process of non serializable injected bean with keyword 'transient'

我在使用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();
    }
}

看截圖:

屏蔽1

Up :序列化之前的對象;

Down :序列化后的對象

我們可以看到瞬態字段為null (向上)。 非臨時字段似乎在序列化后已重新注入對象。 對於我的應用程序,非瞬態場的行為可以正常工作。 參見示例函數showMessage2 瞬態字段將在showMessage()方法中導致NullPointerException

現在我有以下問題。 在我的項目中,對象的序列化非常重要,我對有助於檢測序列化問題的所有功能都很滿意。 我的IDE(Intellij)顯示非瞬態字段: Screen2 根據我的測試結果,我無法使用關鍵字“ transient”,我的應用程序無法正常工作。 沒有關鍵字“ transient”,該應用程序將運行,但是我無法使用代碼分析功能。

我的問題。 我在測試案例中是否錯過了一些常規的東西? 處理這些情況的最佳方法是什么? 測試演員表中的這兩個選項對我來說都不是真的可用。

您可以使記錄器成為靜態最終記錄,並避免在此處向記錄器添加注釋答案

transient關鍵字與CDI結合使用意味着僅在首先實例化此類對象時才將其注入該字段。 例如,首次創建時。

如果在此之后的任何時間需要對對象進行序列化/反序列化, 則不會重新注入 transient字段(而另一個字段將是-這就是您在另一個字段中觀察的對象)。

如果您銷毀了這種bean並重新實例化它(例如,會話bean過期),那么transient字段將再次注入直到第一次序列化為止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM