How to perform a DB cleanup operation upon shutdow

2019-08-21 16:53发布

问题:

I have an EJB app. which basically has to execute a SQL query when it is shutdown. A shutdown hook would presumably work, but that way I can't use injected entitymanager/datasource etc.

Is there a way to provide a shutdown hook that can invoke methods on EJB bean?

Our EJB container is JBoss5.1.

Thanks!

回答1:

for ejbs the approach would be same as what zwei has mentioned, but to add an initializaiton or cleanup ejb with a method having annotation PreDestroy



回答2:

It looks like this works: (EDIT: For some reason the previously posted answer did not work with JBoss5.1. This works.)

    public class SomeServlet extends GenericServlet {
        public void destroy(){
            InitialContext ctx = null;
            try{
                ctx = new InitialContext();
                DataSource ds = (DataSource)ctx.lookup("java:/someDataSource");
                doStuff();
            }catch(Exception e){
                log.error("Bad things happened",e);
            }

            finally{
                try {
                    ctx.close();
                } catch (NamingException e) {
                    e.printStackTrace();
                }
            }
         }//destroy()
    }//class


标签: java jboss ejb