public interface Scope { Object get(String name, ObjectFactory objectFactory);//根据名称及创建工厂得到一个Bean实例 Object remove(String name);//删除一个指定名称的Bean } |
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, void registerScope(String scopeName, Scope scope);//往Bean工厂中添加一个新的范围(默认只有两种范围: singleton及prototype) void destroyScopedBean(String beanName);//销毁B ean工厂中范围Bean } |
String scopeName = mergedBeanDefinition.getScope(); //取得当前Bean的范围,也即在定义中的scope=”request”的部分。 Scope scope = (Scope) this.scopes.get(scopeName);//得到Bean工厂中的范围处理器 if (scope == null) { throw new IllegalStateException("No Scope registered for scope + scopeName + "); } try { //使用scope.get(beanName,ObjectFactory)从指定的范围中得到或创建Bean实例 Object scopedInstance = scope.get(beanName, new ObjectFactory() { public Object getObject() throws BeansException { beforePrototypeCreation(beanName);//前拦截 try { return createBean(beanName, mergedBeanDefinition, args); //调用子类的createBean实现真正的Bean创建工作 } finally { afterPrototypeCreation(beanName);//后拦截 } } }); bean = getObjectForBeanInstance(scopedInstance, name, mergedBeanDefinition);//返回正确类型的Bean实例 } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Scope + scopeName + is not active", ex); } |
public interface WebApplicationContext extends ApplicationContext { String SCOPE_REQUEST = "request"; String SCOPE_SESSION = "session"; String SCOPE_GLOBAL_SESSION = "globalSession"; } |
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { beanFactory.registerScope(SCOPE_REQUEST, new RequestScope());//注册request类型的Bean beanFactory.registerScope(SCOPE_SESSION, new SessionScope(false));//注册session类型的Bean beanFactory.registerScope(SCOPE_GLOBAL_SESSION, new SessionScope(true));//注册glogalsession 的Bean } |