问题
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 retrieve statistics until the next run completed.
Does Java EE 7 provide a simple way to keep application state so that it will be available after redeployment, similar to an in-memory database? As it is only one big object (list), I would prefer something simpler (and maybe better performing too) than a database.
回答1:
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");
来源:https://stackoverflow.com/questions/27804742/simple-ways-to-keep-data-on-redeployment-of-java-ee-7-web-application