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>

    啦啦啦

  • 相关阅读:
    bzoj2669 [cqoi2012]局部极小值 状压DP+容斥
    bzoj2560 串珠子 状压DP
    bzoj2004 [Hnoi2010]Bus 公交线路 矩阵快速幂+状压DP
    「校内训练 2019-04-23」越野赛车问题 动态dp+树的直径
    bzoj5210 最大连通子块和 动态 DP + 堆
    动态 DP 学习笔记
    bzoj4987 Tree 树上背包
    bzoj1190 [HNOI2007]梦幻岛宝珠 背包
    bzoj1004 [HNOI2008]Cards Burnside 引理+背包
    bzoj4922 [Lydsy1706月赛]Karp-de-Chant Number 贪心+背包
  • 原文地址:https://www.cnblogs.com/ClassNotFoundException/p/6388421.html
Copyright © 2011-2022 走看看