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>

    啦啦啦

  • 相关阅读:
    BZOJ 2142: 礼物 [Lucas定理]
    HDU 4349 Xiao Ming's Hope [Lucas定理 二进制]
    HDU 3944 DP? [Lucas定理 诡异的预处理]
    HDU 3037 Saving Beans [Lucas定理]
    HDU 4372 Count the Buildings [第一类斯特林数]
    整理一点与排列组合有关的问题[组合数 Stirling数 Catalan数]
    ZOJ 3557 & BZOJ 2982 combination[Lucas定理]
    BZOJ 3790: 神奇项链 [Manacher 贪心]
    CF 2015 ICL, Finals, Div. 1 J. Ceizenpok’s formula [Lucas定理]
    HDU 1573 X问题 [中国剩余定理]
  • 原文地址:https://www.cnblogs.com/ClassNotFoundException/p/6388421.html
Copyright © 2011-2022 走看看