zoukankan      html  css  js  c++  java
  • 8 -- 深入使用Spring -- 2...2 指定Bean的作用域

          8.2.2 指定Bean的作用域

            当使用XML 配置方式来配置Bean实例时,可以通过scope来指定Bean实例的作用域,没有指定scope属性的Bean实例作用域默认是singleton。

            当采用零配置方式来管理Bean实例时,可使用@Scope Annotation,只要在该Annotation中提供作用域的名称即可。

    package edu.pri.lime._8_2_2.bean.impl;
    
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Component;
    
    import edu.pri.lime._8_2_2.bean.Axe;
    
    @Scope("prototype")
    @Component
    public class SteelAxe implements Axe{
    
        public String chop() {
            return null;
        }
    
    }

            在一些极端的情况下,如果不想使用基于Annotation的方式来指定作用域,而是希望提供自定义的作用域解析器,让自定义的解析器实现ScopeMetadataResolver接口,并提供自定义的作用域解析策略,然后在配置扫描器时指定解析器的全限定类名即可。

            Class : MyScopeMetadataResolver

    package edu.pri.lime._8_2_2.bean.impl;
    
    import org.springframework.beans.factory.config.BeanDefinition;
    import org.springframework.context.annotation.ScopeMetadata;
    import org.springframework.context.annotation.ScopeMetadataResolver;
    
    public class MyScopeMetadataResolver implements ScopeMetadataResolver {
    
        public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
            return null;
        }
    
    }

            XML : 

    <?xml version="1.0" encoding="UTF-8"?>
    <!-- Spring 配置文件的根元素,使用Spring-beans-4.0.xsd语义约束 -->
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    
        <!-- 自动扫描指定包及其子包下的所有Bean类。 -->
        <context:component-scan base-package="edu.pri.lime._8_2_1.bean" scope-resolver="edu.pri.lime._8_2_2.bean.impl.MyScopeMetadataResolver" />
        
    
    </beans>

    啦啦啦

  • 相关阅读:
    expandablelistview学习在listView里面嵌套GridView
    App数据格式之解析Json
    不应和应该在SD卡应用应用
    9 个用来加速 HTML5 应用的方法
    Android设计模式系列-索引
    ObjectiveC语法快速参考
    App列表显示分组ListView
    进程、线程和协程的图解
    Python多进程原理与实现
    Python多线程的原理与实现
  • 原文地址:https://www.cnblogs.com/ClassNotFoundException/p/6388421.html
Copyright © 2011-2022 走看看