1 16 17 package org.springframework.context.support; 18 19 import org.apache.commons.logging.Log; 20 import org.apache.commons.logging.LogFactory; 21 22 import org.springframework.beans.BeansException; 23 import org.springframework.context.ApplicationContext; 24 import org.springframework.context.ApplicationContextAware; 25 import org.springframework.context.ApplicationContextException; 26 27 47 public abstract class ApplicationObjectSupport implements ApplicationContextAware { 48 49 50 protected final Log logger = LogFactory.getLog(getClass()); 51 52 53 private ApplicationContext applicationContext; 54 55 56 private MessageSourceAccessor messageSourceAccessor; 57 58 59 public final void setApplicationContext(ApplicationContext context) throws BeansException { 60 if (context == null && !isContextRequired()) { 61 this.applicationContext = null; 63 this.messageSourceAccessor = null; 64 } 65 else if (this.applicationContext == null) { 66 if (!requiredContextClass().isInstance(context)) { 68 throw new ApplicationContextException( 69 "Invalid application context: needs to be of type [" + requiredContextClass().getName() + "]"); 70 } 71 this.applicationContext = context; 72 this.messageSourceAccessor = new MessageSourceAccessor(context); 73 initApplicationContext(); 74 } 75 else { 76 if (this.applicationContext != context) { 78 throw new ApplicationContextException( 79 "Cannot reinitialize with different application context: current one is [" + 80 this.applicationContext + "], passed-in one is [" + context + "]"); 81 } 82 } 83 } 84 85 92 protected boolean isContextRequired() { 93 return false; 94 } 95 96 102 protected Class requiredContextClass() { 103 return ApplicationContext.class; 104 } 105 106 115 protected void initApplicationContext() throws BeansException { 116 } 117 118 119 122 public final ApplicationContext getApplicationContext() throws IllegalStateException { 123 if (this.applicationContext == null && isContextRequired()) { 124 throw new IllegalStateException ( 125 "ApplicationObjectSupport instance [" + this + "] does not run in an ApplicationContext"); 126 } 127 return applicationContext; 128 } 129 130 135 protected final MessageSourceAccessor getMessageSourceAccessor() throws IllegalStateException { 136 if (this.messageSourceAccessor == null && isContextRequired()) { 137 throw new IllegalStateException ( 138 "ApplicationObjectSupport instance [" + this + "] does not run in an ApplicationContext"); 139 } 140 return this.messageSourceAccessor; 141 } 142 143 } 144 | Popular Tags |