Spring 框架Bean支持以下五个作用域:
下面介绍两种作用域,singleton和protoype
singleton作用域
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作用域
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.java
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 }
运行输出
Your Message : I‘m object A 12:06:56.273 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean ‘helloWorld‘ Your Message : I‘m object A
prototype作用域
如果作用域设置为 prototype,每次创建对象实例只针对当前实例配置Bean,getBean是不同的bean。
将上述的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 13:52:03.767 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean ‘helloWorld‘ 13:52:03.767 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean ‘helloWorld‘ Your Message : null
时间: 2024-10-02 10:00:00