Spring阶段性学习总结(三)Bean的作用域

 1 public class Person {
 2     private String name;
 3     private int age;
 4 
 5     public String getName() {
 6         return name;
 7     }
 8 
 9     public void setName(String name) {
10         this.name = name;
11     }
12 
13     public int getAge() {
14         return age;
15     }
16 
17     public void setAge(int age) {
18         this.age = age;
19     }
20 
21     @Override
22     public String toString() {
23         return "Person{" +
24                 "name='" + name + '\'' +
25                 ", age=" + age +
26                 '}';
27     }
28 }
 1 package SpringScop;
 2 
 3 import org.springframework.context.support.ClassPathXmlApplicationContext;
 4 
 5 public class Main {
 6     public static void main(String[] args) {
 7         ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("SpringScop/spring-scop.xml");
 8         Person person = (Person) ctx.getBean("person");
 9         Person person1 = (Person) ctx.getBean("person");
10         System.out.println(person == person1);
11     }
12 }

 

 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" xmlns:p="http://www.springframework.org/schema/p"
 4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 5 
 6     <!--singleton 作用域是把Bean存放在IOC容器中 供调用的共享,单例模式-->
 7     <!--prototype 作用域是在每次调用Bean时会重新创建一个Bean 相当于new,多线程生成多个实例-->
 8     <bean id="person" class="SpringScop.Person"
 9           p:name="张浩" p:age="20" scope="prototype"></bean>
10 
11     <bean id="person1" class="SpringScop.Person"
12           p:name="张浩" p:age="20"></bean>
13 </beans>

 

posted @ 2019-09-20 14:48  我叫张小凡  阅读(183)  评论(0编辑  收藏  举报