1 16 17 package org.springframework.test; 18 19 import java.util.HashMap ; 20 import java.util.Map ; 21 22 import org.springframework.context.ConfigurableApplicationContext; 23 import org.springframework.util.Assert; 24 import org.springframework.util.ObjectUtils; 25 26 51 public abstract class AbstractSpringContextTests extends ConditionalTestCase { 52 53 58 private static Map contextKeyToContextMap = new HashMap (); 59 60 61 64 public AbstractSpringContextTests() { 65 } 66 67 70 public AbstractSpringContextTests(String name) { 71 super(name); 72 } 73 74 75 82 public final void addContext(Object key, ConfigurableApplicationContext context) { 83 Assert.notNull(context, "ApplicationContext must not be null"); 84 contextKeyToContextMap.put(contextKeyString(key), context); 85 } 86 87 91 protected final boolean hasCachedContext(Object contextKey) { 92 return contextKeyToContextMap.containsKey(contextKey); 93 } 94 95 100 protected final ConfigurableApplicationContext getContext(Object key) throws Exception { 101 String keyString = contextKeyString(key); 102 ConfigurableApplicationContext ctx = 103 (ConfigurableApplicationContext) contextKeyToContextMap.get(keyString); 104 if (ctx == null) { 105 ctx = loadContext(key); 106 ctx.registerShutdownHook(); 107 contextKeyToContextMap.put(keyString, ctx); 108 } 109 return ctx; 110 } 111 112 118 protected final void setDirty(Object contextKey) { 119 String keyString = contextKeyString(contextKey); 120 ConfigurableApplicationContext ctx = 121 (ConfigurableApplicationContext) contextKeyToContextMap.remove(keyString); 122 if (ctx != null) { 123 ctx.close(); 124 } 125 } 126 127 128 133 protected String contextKeyString(Object contextKey) { 134 return ObjectUtils.nullSafeToString(contextKey); 135 } 136 137 143 protected abstract ConfigurableApplicationContext loadContext(Object key) throws Exception ; 144 145 } 146 | Popular Tags |