源码
package java.util;
public interface Enumeration<E> {
boolean hasMoreElements();
E nextElement();
}
Enumeration的遍历
Spring之ContextCleanupListener源码
package org.springframework.web.context;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.DisposableBean;
public class ContextCleanupListener implements ServletContextListener {
private static final Log logger = LogFactory.getLog(ContextCleanupListener.class);
@Override
public void contextInitialized(ServletContextEvent event) {
}
@Override
public void contextDestroyed(ServletContextEvent event) {
cleanupAttributes(event.getServletContext());
}
static void cleanupAttributes(ServletContext sc) {
Enumeration<String> attrNames = sc.getAttributeNames();
while (attrNames.hasMoreElements()) {
String attrName = attrNames.nextElement();
if (attrName.startsWith("org.springframework.")) {
Object attrValue = sc.getAttribute(attrName);
if (attrValue instanceof DisposableBean) {
try {
((DisposableBean) attrValue).destroy();
}
catch (Throwable ex) {
logger.error("Couldn't invoke destroy method of attribute with name '" + attrName + "'", ex);
}
}
}
}
}
}
相关源码
- org.apache.catalina.core.ApplicationContext.getAttributeNames()方法
@Override
public Enumeration<String> getAttributeNames() {
Set<String> names = new HashSet<>();
names.addAll(attributes.keySet());
return Collections.enumeration(names);
}
- java.util.Collections.enumeration(Collection)方法
public static <T> Enumeration<T> enumeration(final Collection<T> c) {
return new Enumeration<T>() {
private final Iterator<T> i = c.iterator();
public boolean hasMoreElements() {
return i.hasNext();
}
public T nextElement() {
return i.next();
}
};
}