I have a Spring controller bean set to a session scope, it looks somewhat like this:
@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
}
}
It seems Spring does not call @PostConstruct after de-serialisation, this causes my “log” field to become null and throw a NullPointerException in my doGet() method.
How do you usually deal with non-serialisable fields like the logger in session-scoped beans? Do I need to implement some session aware interface to make this work?
I think a typical way is to use
readObject()to initializetransientfields, no matter whether it’s a Spring bean or not: