Java框架spring 学习笔记(二):Bean的做用域

Spring 框架Bean支持如下五个做用域:java

下面介绍两种做用域,singleton和protoypespring

 

singleton做用域sql

singleton做用域为默认做用域,在同一个ioc容器内getBean是同一个bean,若是建立一个singleton做用域Bean定义的对象实例,该实例将存储在该Bean的缓存中,那么之后全部针对该 bean的请求和引用都返回缓存对象。缓存

编写HelloWorld.java框架

 1 package com.example.spring;
 2 
 3 public class HelloWorld {
 4     private String message;
 5     public void setMessage(String message){
 6         this.message  = message;
 7     }
 8     public void getMessage(){
 9         System.out.println("Your Message : " + message);
10     }
11 }

编写Beans.xml,设置为singleton做用域this

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
5 
6     <bean id="helloWorld" class="com.example.spring.HelloWorld" scope="singleton">
7     </bean>
8 </beans>

编写Application.javaspa

 1 package com.example.spring;
 2 
 3 import org.springframework.beans.factory.BeanFactory;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 public class Application {
 7     public static void main(String[] args) {
 8         //bean配置文件所在位置 D:\\IdeaProjects\\spring\\src\\Beans.xml
 9         //使用BeanFactory容器
10         BeanFactory factory = new ClassPathXmlApplicationContext("file:D:\\IdeaProjects\\spring\\src\\Beans.xml");
11         HelloWorld objA = (HelloWorld)factory.getBean("helloWorld");
12         objA.setMessage("I'm object A");
13         objA.getMessage();
14         HelloWorld objB = (HelloWorld) factory.getBean("helloWorld");
15         objB.getMessage();
16     }
17 }

运行输出prototype

Your Message : I'm object A
Your Message : I'm object A

 

prototype做用域code

若是做用域设置为 prototype,每次建立对象实例只针对当前实例配置Bean,getBean是不一样的bean。xml

将上述的Beans.xml,设置为prototype做用域

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
5 
6     <bean id="helloWorld" class="com.example.spring.HelloWorld" scope="prototype">
7     </bean>
8 </beans>

运行输出:

Your Message : I'm object A
Your Message : null
相关文章
相关标签/搜索