2012-09-21 60 views
1

我有一個春天的controller bean設置到會話範圍,它看起來有點像這樣:瞬態領域

@Controller 
@Scope(WebApplicationContext.SCOPE_SESSION) 
@RequestMapping("/test") 
public class SessionTestController implements Serializable { 

    private static final long serialVersionUID = -7735095657091576437L; 

    private transient Log log; 

    @PostConstruct 
    public void initialise() { 
     log = LogFactory.getLog(getClass()); 
    } 

    @RequestMapping(method=RequestMethod.GET) 
    @ResponseBody 
    public String doGet() throws InterruptedException { 
     log.warn("This line will fail after deserialisation..."); // Causes NPE 
    } 

} 

看來春季反序列化之後不會調用@PostConstruct,這將導致我的「日誌」字段變爲空,並在我的doGet()方法中拋出NullPointerException。

通常如何處理不可序列化的字段,如會話範圍的bean中的記錄器?我是否需要實現一些會話感知界面來使其工作?

回答

1

我認爲,一個典型的方法是使用readObject()初始化transient領域,不管它是一個Spring bean與否:

private void readObject(ObjectInputStream stream) 
    throws IOException, ClassNotFoundException { 
    stream.defaultReadObject(); 
    initializeTransientFields(); 
} 
+0

,我想我已經下降與此@PostConstruct嘗試一個壞的路徑。我希望這是正確的解決方案。 – seanhodges

+0

在我的例子中,我讓記錄器靜態並且修復了類名參數'LogFactory.getLog(SessionTestController.class);',但是其他一些字段現在使用'readObject'。謝謝! – seanhodges