Simple ways to keep data on redeployment of Java EE 7 web application

后端 未结 1 1968
孤独总比滥情好
孤独总比滥情好 2021-01-22 19:22

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

相关标签:
1条回答
  • 2021-01-22 20:12

    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");
    
    0 讨论(0)
提交回复
热议问题