您的位置:首页 > 其它

Bean的作用域

2017-08-16 20:18 204 查看
1.在默认情况下所有bean都是单列形式。也就是说不管一个bean注入到其他bean多少次每一次注入的都是同一个实例。

2.单列(Singleton):在整个应用中,只创建一个bean实例。



代码演示

package com.learnSpring06;

public class Student {

private String message;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

}

<?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"> 
<!-- 默认为Singleton模式 -->
<bean  id="student01"  class="com.learnSpring06.Student">
<property name="message"  value="我是张三"> </property>

</bean>

</beans>

package com.learnSpring06;

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

public class testStudent {

@Test
public void testStudent(){

ApplicationContext context=new ClassPathXmlApplicationContext("bean04.xml");
//第一次获得对象
Student student=(Student) context.getBean("student01");
System.out.println(student.getMessage());

//再一次获取student对象
Student student1 = (Student) context.getBean("student01");
System.out.println(student.getMessage());

//如果打印结果为true表明获取为同一个对象
System.out.println(student.equals(student1));

}
}

控制台输出结果:

我是张三
我是张三
true


原型(Prototype):每一次注入或通过 Spring应用上下文获取的时候,都会创建一个新的bean实例。



代码演示

package com.learnSpring06;

public class Student {

private String message;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

}

<?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"> 
<!-- 默认为Singleton模式 -->
<bean  id="student01"  class="com.learnSpring06.Student"  scope="prototype">
<property name="message"  value="我是张三"> </property>

</bean>

</beans>

p
b8ff
ackage com.learnSpring06;

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

public class testStudent {

@Test
public void testStudent(){

ApplicationContext context=new ClassPathXmlApplicationContext("bean04.xml");
Student student=(Student) context.getBean("student01");
System.out.println(student.getMessage());

//再一次获取student对象
Student student1 = (Student) context.getBean("student01");
System.out.println(student.getMessage());

//如果打印结果为false表明获取为不同对象
System.out.println(student.equals(student1));

}
}

控制台输出结果为:

我是张三
我是张三
false
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: