Bean的作用域
在Spring中,那些组成应用程序的主体及由Spring IoC容器所管理的对象,被称之为bean。简单地讲,bean就是由IoC容器初始化、装配及管理的对象 .
1. 单例模式(Singleton),spring默认的机制,单线程使用,需要重点掌握。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--c(构造:Constructor)命名空间:属性依然要设置set方法-->
<bean id="user3" class="com.kuang.pojo.User" c:name="祥子" c:age="35" scope="singleton"/>
</beans>
测试类:
/* Bean的作用域的test*/
@Test
public void testBean() {
ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
User user1 = context.getBean("user3", User.class);
User user2 = context.getBean("user3", User.class);
System.out.println(user1==user2);
}
测试类的执行结果为true。
2. 原型模式(prototype),每次从容器中get的时候,都会产生一个新对象,多线程使用,需要掌握
User.java
package com.kuang.pojo;
public class User {
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
userBeans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--c(构造:Constructor)命名空间:属性依然要设置set方法-->
<bean id="user3" class="com.kuang.pojo.User" c:name="祥子" c:age="35" scope="prototype"/>
</beans>
测试类:
/* Bean的作用域的test*/
@Test
public void testBean() {
ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
User user1 = context.getBean("user3", User.class);
User user2 = context.getBean("user3", User.class);
System.out.println(user1==user2);
}
测试类的执行结果是false。