DeregisterServiceProviderServletListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent sce) { final ClassLoader classLoader = getClass().getClassLoader(); final ServiceRegistry serviceRegistry = IIORegistry.getDefaultInstance(); Iterator<Class<?>> categories = IIORegistry.getDefaultInstance().getCategories(); if (categories != null) { while (categories.hasNext()) { Class<?> category = categories.next(); Iterator<?> providers = serviceRegistry.getServiceProviders(category, false); if (providers != null) { List providersToRemove = new ArrayList(); while (providers.hasNext()) { Object provider = providers.next(); if (provider != null && classLoader.equals(provider.getClass().getClassLoader())) { providersToRemove.add(provider); } } for (Object provider : providersToRemove) { serviceRegistry.deregisterServiceProvider(provider); LOGGER.info("deregistered service provider {} from category {}", provider.getClass().getName(), category.getName()); } } } } } DeregisterServiceProviderServletListener(); @Override void contextInitialized(ServletContextEvent sce); @Override void contextDestroyed(ServletContextEvent sce);  }
@Test public void testSomeMethod() { IIORegistry iioRegistry = IIORegistry.getDefaultInstance(); DeregisterServiceProviderServletListener l = new DeregisterServiceProviderServletListener(); List<ImageInputStreamSpi> iBefore = convertToList(ServiceRegistry.lookupProviders(ImageInputStreamSpi.class, getClass().getClassLoader())); List<ImageOutputStreamSpi> oBefore = convertToList(ServiceRegistry.lookupProviders(ImageOutputStreamSpi.class, getClass().getClassLoader())); List<ImageInputStreamSpi> iiBefore = convertToList(iioRegistry.getServiceProviders(ImageInputStreamSpi.class, false)); List<ImageOutputStreamSpi> ooBefore = convertToList(iioRegistry.getServiceProviders(ImageOutputStreamSpi.class, false)); l.contextDestroyed(null); List<ImageInputStreamSpi> iiAfter = convertToList(iioRegistry.getServiceProviders(ImageInputStreamSpi.class, false)); List<ImageOutputStreamSpi> ooAfter = convertToList(iioRegistry.getServiceProviders(ImageOutputStreamSpi.class, false)); List<ImageInputStreamSpi> iAfter = convertToList(ServiceRegistry.lookupProviders(ImageInputStreamSpi.class, getClass().getClassLoader())); List<ImageOutputStreamSpi> oAfter = convertToList(ServiceRegistry.lookupProviders(ImageOutputStreamSpi.class, getClass().getClassLoader())); }