spring的Bean配置项和作用域

singleton作用域是默认的作用域,如果想要修改默认作用域可以再<bean>中添加属性scope="pototype"来更改作用域

global session作用域:应用于多个系统并存的情况下

案例:

  1、创建一个java project

  2、创建一个包,再包中创建一个BeanScop.java

package org.bean.example;

public class BeanScope {
    public void save(){
        System.out.println("beanScope:"+this.hashCode());
    }
}

  3、在创建一个TestBeanScope.java,该类必须继承UnitTestBase.java类(代码:https://www.cnblogs.com/myfaith-feng/p/9211290.html)

package org.bean.example;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.util.test.UnitTestBase;

@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanScope extends UnitTestBase{
    
    public TestBeanScope() {
        super("classpath*:spring-ioc.xml");
    }
    
    @Test
    public void test(){
        BeanScope beanScope = super.getBean("beanScope");
        beanScope.save();
        
        BeanScope beanScope1 = super.getBean("beanScope");
        beanScope1.save();
    }
    
    @Test
    public void test2(){
        BeanScope beanScope = super.getBean("beanScope");
        beanScope.save();
    }
    
}

  4、在项目下创建一个spring-ioc.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"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" xmlns:tx="http://www.springframework.org/schema/tx">

    <bean id="beanScope" class="org.bean.example.BeanScope" scope="singleton"></bean>
</beans>

  5、配置的scope="singleton"单例作用域,其输出的hashCode是相同的,但是不同容器中其hashCode就会不一样

猜你喜欢

转载自www.cnblogs.com/myfaith-feng/p/9214452.html