Reputation: 521
How can I delete all items of a MongoDB document on Spring Boot application shutdown or on ServletContext destroyed?
Here is the Spring Boot application file.It is not working:
@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");
}
}
}
In the contextDestroyed method I am trying to remove the item with id "flight-service" but it is not working.
How can I remove all items in a MongoDB database on contextDestroyed or application shutdown?
Upvotes: 1
Views: 1517
Reputation: 521
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);
}
}
Upvotes: 2