Spring之Bean的作用域、使用外部属性文件、mchange-commons-java-0.2.11.jar下载

本文深入探讨了Spring中Bean的作用域,通过三个不同情景展示了Singleton、Prototype等不同作用域的实例和运行结果。同时,文章还详细介绍了如何使用外部属性文件进行配置,包括从db.properties文件加载数据,并在实际应用中展示了配置的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Bean的作用域

在IOC里创建对象的时候,同一个类,只会创建一个实例对象,多次获取同一个类的对象时,实际上获取的都是同一个对象,
两个对象的地址是相同的
car.java
package com.labou3g.bean.scope;
public class Car {
	private String brand;
	private double price;
	public Car() {
		System.out.println("我是构造方法....");
	}
	public String getBrand() {
		return brand;
	}
	public void setBrand(String brand) {
		this.brand = brand;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	@Override
	public String toString() {
		return "Car [brand=" + brand + ", price=" + price + "]";
	}	
}

情景一

bean-scope.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	<bean id="car" class="com.labou3g.bean.scope.Car">
		<property name="brand" value="赤兔马"></property>
		<property name="price" value="1000"></property>
	</bean>
</beans>
Test.java
public class Test {
	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-autowire.xml");
		
		Car car1 = (Car)ctx.getBean("car");
		Car car2 = (Car)ctx.getBean("car");
		System.out.println(car1 == car2);
	}
}
运行结果

在这里插入图片描述

情景二

bean-scope.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="car" class="com.labou3g.bean.scope.Car" scope="singleton">
		<property name="brand" value="赤兔马"></property>
		<property name="price" value="1000"></property>
	</bean>
</beans>
运行结果
和情景一结果一直,因为scope的默认值就是singleton

情景三-prototype

bean-scope.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="car" class
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值