My Java EE 7 web service generates statistics once per day, and because data is stored only in an ApplicationScoped bean, it does not survive redeployment, so clients cannot ret
In the @ApplicationScoped
bean, you can just implement @PreDestroy
to save it to some temporary storage which you then check and read in @PostConstruct
. You can get the container-managed temporary storage location as a servlet context attribute keyed by ServletContext.TEMPDIR.
Here's a kickoff example using JAXB so that the data is saved in reusable XML format.
private Data data;
private File file;
private JAXBContext jaxb;
@Inject
private ServletContext servletContext;
@PostConstruct
public void init() {
File tempdir = (File) servletContext.getAttribute(ServletContext.TEMPDIR);
file = new File(tempdir, "data.xml");
jaxb = JAXBContext.newInstance(Data.class);
if (file.exists()) {
data = (Data) jaxb.createUnmarshaller().unmarshal(file);
}
}
@PreDestroy
public void destroy() {
jaxb.createMarshaller().marshal(data, file);
}
If you happen to deploy to JBoss (WildFly), then you can alternatively also use JBoss-managed data folder, which is a bit more permanent than the location as represented by ServletContext.TEMPDIR
.
String datadir = System.getProperty("jboss.server.data.dir");
file = new File(datadir, "data.xml");