5.1、bean的作用域
5.1.1、单例(默认且常用)
5.1.1.1、配置bean
注意:当bean不配置scope属性时,默认是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="student" class="org.rain.spring.pojo.Student"></bean>
</beans>
5.1.1.2、测试
由控制台日志可知,此时ioc获取到的两个bean本质上是同一个对象
@Test
public void testScope() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-scope.xml");
Student student1 = applicationContext.getBean(Student.class);
Student student2 = applicationContext.getBean(Student.class);
System.out.println(student1 == student2);
}
5.1.2、多例
5.1.2.1、配置bean
<?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">
<!--
scope属性:设置bean的作用域
当属性值为singleton时,在IOC容器中这个bean的对象始终为单实例;且创建对象的时机是IOC容器初始化时
当属性值为prototype时,在IOC容器中这个bean的对象有多个实例;且创建对象的时机是获取bean时
-->
<bean id="student" class="org.rain.spring.pojo.Student" scope="prototype"></bean>
</beans>
5.1.2.2、测试
由控制台日志可知,此时ioc获取到的两个bean本质上是不同的对象
5.1.3、其他作用域
如果是在WebApplicationContext环境下还会有另外两个作用域(但不常用):
-
request:在一个请求范围内有效
-
session:在一个会话范围内有效
5.2、bean的生命周期
5.2.1、创建User类
package org.rain.spring.pojo;
/**
* @author liaojy
* @date 2023/8/3 - 23:59
*/
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
public User() {
System.out.println("生命周期1:创建对象");
}
public User(Integer id, String username, String password, Integer age) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
System.out.println("生命周期2:依赖注入");
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public void initMethod(){
System.out.println("生命周期3:初始化");
}
public void destroyMethod(){
System.out.println("生命周期4:销毁");
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}
5.2.2、配置bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi=&qu