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>

啦啦啦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值