Spring Boot Mongodb在应用程序关闭时删除所有

时间:2019-03-19 14:27:58

标签: spring spring-boot spring-mongodb

如何在Spring Boot应用程序关闭或销毁ServletContext时删除MongoDB文档的所有项目?

这是Spring Boot应用程序文件,它不起作用:

@SpringBootApplication
public class DiscoveryServiceApplication {

    public static void main(String[] args){
        System.setProperty("server.servlet.context-path", "/");
        SpringApplication.run(DiscoveryServiceApplication.class,args);
    }

    @NotNull
    @Bean
    ServletListenerRegistrationBean<ServletContextListener> myServletListener() {
        ServletListenerRegistrationBean<ServletContextListener> srb =
                new ServletListenerRegistrationBean<>();
        srb.setListener(new DiscoveryServiceServletContextListener());
        return srb;
    }


    class DiscoveryServiceServletContextListener implements ServletContextListener {

        Logger logger= Logger.getLogger(com.skyscanner.discovery.config.DiscoveryServiceServletContextListener.class);


        @Override
        public void contextInitialized(ServletContextEvent sce) {
            logger.info("ServletContext initialized");
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce){
            //logger.info("RestAPI repository all items deleted");
            //Optional<RestAPI> query=repository.findById("flight-service");
            //RestAPI restAPI=query.get();

            MongoClient mongoClient = new MongoClient();
            DB database=mongoClient.getDB("skyscannerDiscoveryDB");
            DBCollection collection=database.getCollection("restAPI");

            BasicDBObject query=new BasicDBObject();
            query.append("id","flight-service");
            collection.remove(query);

            logger.info("flight-service deleted");

        }
    }
}

在contextDestroyed方法中,我试图删除ID为“ flight-service”的项目,但它不起作用。

如何在contextDestroyed或应用程序关闭时删除MongoDB数据库中的所有项目?

1 个答案:

答案 0 :(得分:1)

It worked.I added the following code to Spring Boot application.Here is the application:

@SpringBootApplication
public class DiscoveryServiceApplication {

    @Autowired
    private static ApplicationContext context;


    @Component
    public static class ApplicationLifecycle implements Lifecycle{

        @Autowired
        private RestAPIRepository repository;

        Logger logger=Logger.getLogger(ApplicationLifecycle.class);

        @Override
        public void start() {
            logger.info("Application start");
        }

        @Override
        public void stop() {
            logger.info("Application stop");
            repository.deleteAll();

        }

        @Override
        public boolean isRunning() {
            return true;
        }
    }
    public static void main(String[] args){
        System.setProperty("server.servlet.context-path", "/");
        SpringApplication.run(DiscoveryServiceApplication.class,args);

    }
    }