Spring课程 Spring入门篇 3-1 Spring bean装配(上)之bean的配置项及作用域

本节主要讲了四大块

1    bean的作用域

2    bean作用域代码演练

3    单例 多例应用场景

4    bean的配置项

1    bean的作用域

1.1  singleton  :单例

1.2  prototype  :多例

不重要:

1.3  request     :每次http请求创建一个实例且仅在当前request有效

1.4  session     :每次http请求创建,当前session内有效

1.5  global session:基于portlet的web有效(portlet中定义了global session),如果在web中,同session

2    bean作用域代码演练

2.1  singleton作用域实例

实体类:

package com.imooc.bean;

public class BeanScope {
    
    /**
     * say方法测试 哈希码值,判断用的是不是同一块 内存
     */
    public void say(){
        System.out.println("该对象的哈希码为"+this.hashCode());
    }

}

xml配置文件:(红色标注部分为不同)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-init-method="init" default-destroy-method="destroy">

 <bean id="beanScope" class="com.imooc.bean.BeanScope" scope="singleton"></bean>  
<!--<bean id="beanScope" class="com.imooc.bean.BeanScope" scope="prototype"></bean> -->

</beans>

测试类:

package com.imooc.test.ioc.interfaces;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.springframework.cglib.core.Block;

import com.imooc.bean.BeanScope;
import com.imooc.test.base.UnitTestBase;

@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanScope extends UnitTestBase{

    public TestBeanScope() {
        super("classpath*:spring-beanScope.xml");
    }
    
    @Test
    /**
     * 测试单例模式 Signton
     */
    public void testSay(){
        try {
            BeanScope bScope = super.getbean("beanScope");
            bScope.say();
            
            BeanScope bScope2 = super.getbean("beanScope");
            bScope2.say();
        } catch (Exception e) { 
            // TODO: handle exception
        }
    }

}

2.2  prototype作用域实例

实体类(同上)

xml配置文件:(红色标注部分不同)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-init-method="init" default-destroy-method="destroy">

<!-- <bean id="beanScope" class="com.imooc.bean.BeanScope" scope="singleton"></bean> --> 
<bean id="beanScope" class="com.imooc.bean.BeanScope" scope="prototype"></bean> 

</beans>

测试类(同上)

3    单例 多例应用场景

经上边应用可知:

作用域为singleton ,两次打印哈希码值相同,即,只在初始化的时候创建一个实例(即加载上下文context.xml的时候);

作用域为prototype,两次打印哈希码值不同,则每次访问都会创建一个实例。

应用场景:

如果需要回收重要资源(如数据库连接等)应该为配置为singleton,因为单个库的数据库连接只有一个。

如果是有状态的bean应配置为prototype,如生效和失效的客户。

4    bean的配置项

猜你喜欢

转载自www.cnblogs.com/1446358788-qq/p/10422603.html
今日推荐