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

Java框架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 >
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
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 >
7     </bean>
8 </beans>

运行输出:

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

  

 

相关文章:

  • 2022-03-10
  • 2021-10-29
  • 2021-07-26
  • 2021-10-08
  • 2022-01-05
  • 2021-08-06
  • 2021-09-25
  • 2021-11-02
猜你喜欢
  • 2022-01-08
  • 2021-10-04
  • 2021-09-06
  • 2022-01-18
  • 2022-01-04
  • 2021-09-25
  • 2021-12-25
相关资源
相似解决方案