spring4第6课-bean之间的关系+bean的作用范围

总结:

①bean之间的关系有  1,继承; 2,依赖; 3,引用;

②bean的作用范围(scope)

1,singleton Spring ioc 容器中仅有一个 Bean 实例,Bean 以单例的方式存在;(重点)
2,prototype 每次从容器中调用 Bean 时,都返回一个新的实例;(重点)
3,request 每次 HTTP 请求都会创建一个新的 Bean;
4,session 同一个 HTTP Session 共享一个 Bean;
5,global session 同一个全局 Session 共享一个 Bean,一般用于 Portlet 应用环境;(使用不多)
6,application 同一个 Application 共享一个 Bean;

详解如下:↓↓↓↓↓

①bean之间的关系有  1,继承; 2,依赖; 3,引用;

结合代码看比较好理解



   
   
      
   
   
    abstract="true"> 
      
       
     
           
   

   

   parent="abstractPeople" depends-on="autority">
      
      
   
   
   
      
      
      value="20">  
   
    
   

②bean的作用范围(scope)

1,singleton Spring ioc 容器中仅有一个 Bean 实例,Bean 以单例的方式存在;(重点)
2,prototype 每次从容器中调用 Bean 时,都返回一个新的实例;(重点)
3,request 每次 HTTP 请求都会创建一个新的 Bean;
4,session 同一个 HTTP Session 共享一个 Bean;
5,global session 同一个全局 Session 共享一个 Bean,一般用于 Portlet 应用环境;(使用不多)
6,application 同一个 Application 共享一个 Bean;

详解如下:↓↓↓↓↓

代码1:bean.xml  关键字是   scope="singleton"  spring的默认值是singleton



	
	
		
	

代码2: bean类

package com.java1234.entity;

public class Dog {
	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
		
}

代码3:测试类

package com.java1234.test;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.java1234.entity.Dog;

public class T {

	private ApplicationContext ac;

	@Before
	public void setUp() throws Exception {
		ac=new ClassPathXmlApplicationContext("beans.xml");
	}

	@Test
	public void test1() {
		Dog dog=(Dog)ac.getBean("dog");
		Dog dog2=(Dog)ac.getBean("dog");
		System.out.println(dog==dog2);
	}
	

}

运行结果: bean.xml内容不同,输出结果不同
scope="singleton" 单例模式时,每次都取1个同一个dog对象,所以两次的dog对象相同,输出true
scope="prototype" 多例模式时,每次都会取1个新的dog对象,所以两个dog对象不同,输出false

你可能感兴趣的:(spring,java,spring)