Spring会话范围控制器中的瞬态字段

时间:2012-09-21 11:23:38

标签: spring session logging spring-3

我有一个Spring控制器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
    }

}

在反序列化后,Spring似乎没有调用@PostConstruct,这会导致我的“log”字段变为null并在我的doGet()方法中抛出NullPointerException。

您通常如何处理非可序列化字段,例如会话范围内的bean中的记录器?我是否需要实现一些会话感知界面才能使其正常工作?

1 个答案:

答案 0 :(得分:2)

我认为一种典型的方法是使用readObject()来初始化transient字段,无论它是否是Spring bean:

private void readObject(ObjectInputStream stream)
     throws IOException, ClassNotFoundException {
    stream.defaultReadObject();
    initializeTransientFields();
}
相关问题