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

时间:2023-03-08 23:20:21
Java框架spring 学习笔记(二):Bean的作用域

Spring 框架Bean支持以下五个作用域:

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

下面介绍两种作用域,singleton和protoype

singleton作用域

singleton作用域为默认作用域,在同一个ioc容器内getBean是同一个bean,如果创建一个singleton作用域Bean定义的对象实例,该实例将存储在该Bean的缓存中,那么以后所有针对该 bean的请求和引用都返回缓存对象。

编写HelloWorld.java

 package com.example.spring;

 public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}

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

 <?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"> <bean id="helloWorld" class="com.example.spring.HelloWorld" scope="singleton">
</bean>
</beans>

编写Application.java

 package com.example.spring;

 import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Application {
public static void main(String[] args) {
//bean配置文件所在位置 D:\\IdeaProjects\\spring\\src\\Beans.xml
//使用BeanFactory容器
BeanFactory factory = new ClassPathXmlApplicationContext("file:D:\\IdeaProjects\\spring\\src\\Beans.xml");
HelloWorld objA = (HelloWorld)factory.getBean("helloWorld");
objA.setMessage("I'm object A");
objA.getMessage();
HelloWorld objB = (HelloWorld) factory.getBean("helloWorld");
objB.getMessage();
}
}

运行输出

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

prototype作用域

如果作用域设置为 prototype,每次创建对象实例只针对当前实例配置Bean,getBean是不同的bean。

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

 <?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"> <bean id="helloWorld" class="com.example.spring.HelloWorld" scope="prototype">
</bean>
</beans>

运行输出:

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