10.Bean对象的作用域和生命周期
bean scope属性
bean scope属性用于决定对象何时被创建与作用范围,bean scope配置将影响容器内对象的数量,默认情况下bean会在IoC容器创建后自动实例化,全局唯一。
bean scope用法
<bean id="bookDao" class="com.spring.ioc.bookshop.dao.BookDaoOracleImpl" scrope="prototype"/>
bean scope属性清单
singleton与prototype对比
singleton单例模式在Ioc容器初始化过程中创建bean对象,prototype多例模式在Ioc容器获取bean的时候创建bean对象,某一个属性在运行过程中如果恒定不变,则设置成单例,如果属性在运行过程中不断变化,则设置成多例。
bean生命周期
package com.spring.ioc.entity;
import com.sun.org.apache.xpath.internal.operations.Or;
public class Order {
private Float price;
private Integer quantity;
private Float total;
public Order(){
System.out.println("构造方法 创建Order对象:"+this);
}
public void init(){
System.out.println("执行init()方法");
total = price * quantity;
}
public void destroy(){
System.out.println("释放与订单对象相关的资源");
}
public void pay(){
System.out.println("pay()方法 订单金额为:"+total);
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
System.out.println("setPrice 设置price:"+price);
this.price = price;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
System.out.println("setQuantity 设置quantity:"+quantity);
this.quantity = quantity;
}
public Float getTotal() {
return total;
}
public void setTotal(Float total) {
this.total = total;
}
}
<?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="order1" class="com.spring.ioc.entity.Order" init-method="init" destroy-method="destroy">
<property name="price" value="19.8"/>
<property name="quantity" value="1000"/>
</bean>
</beans>
package com.spring.ioc;
import com.spring.ioc.entity.Order;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringApplication {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
System.out.println("=======Ioc容器初始化========");
Order order1 = context.getBean("order1", Order.class);
order1.pay();
((ClassPathXmlApplicationContext) context).registerShutdownHook();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!