Spring之IoC

提起Spring,就容易想到IoC和AOP,当然,在这里我们只针对IoC做出相应解释。

  • 什么是IoC?
    IoC即控制反转,那控制反转到底是什么呢?
    在传统的程序设计中,我们如果要创建对象是直接通过new的方式来获得的,而IoC则是通过容器来创建对象的,即对象的产生交由容器来管理。

通过一个例子来讲解IoC的使用

  • 传统方式
    创建一个Car类
public class Car {
	private float price;
	private String color;
	private String name;
}

调用构造函数创建对象

Car car = new Car();
  • 通过IoC容器方式创建
  • 无参构造
<!-- 配置car对象 -->
<bean id="car" class="com.lhg.spring.Car"></bean>

通过id获取对象

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Car car = (Car) applicationContext.getBean("car");
System.out.println(car);

程序在加载 spring.xml 时创建 car 对象,通过反射机制调用无参构造函数,所有要求交给 IoC 容器管理的类必须有无参构造函数。
--------执行结果

Car [price=0.0, color=null, name=null]

此时可以看到结果都为空,因为调用无参构造只会创建对象而不会进行赋值,那我们只需在spring.xml中配置即可。

<!-- 配置car对象 -->
<bean id="car" class="com.lhg.spring.Car">
	<property name="price" value="200000.0"></property>
	<property name="color" value="blue"></property>
	<property name="name" value="superCar"></property>
</bean>

执行结果

Car [price=200000.0, color=blue, name=superCar]
  • 有参构造
    现在实体中创建有参构造
public Car(float price, String color, String name) {
		super();
		this.price = price;
		this.color = color;
		this.name = name;
	}

在spring.xml中进行配置

<!-- 配置car对象 -->
<bean id="car" class="com.lhg.spring.Car">
	<constructor-arg name="price" value="200000.0"></constructor-arg>
	<constructor-arg name="color" value="blue"></constructor-arg>
	<constructor-arg name="name" value="superCar"></constructor-arg>
</bean>

当然,name属性处我们也可以用index下标进行对应

<!-- 配置car对象 -->
<bean id="car" class="com.lhg.spring.Car">
	<constructor-arg index="0" value="200000.0"></constructor-arg>
	<constructor-arg index="1" value="blue"></constructor-arg>
	<constructor-arg index="2" value="superCar"></constructor-arg>
</bean>

执行结果均是

Car [price=200000.0, color=blue, name=superCar]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值