1. 通过构造方法创建
(1)无参构造创建:默认情况
(2)有参构造创建:需要明确配置
① 需要在类中提供有参构造方法
② 在applicationContext.xml中设置调用哪个构造方法创建的对象
③ 如果设定的条件匹配多个构造方法执行最后的构造方法
④ index:参数的索引,从零开始
⑤ name:实体类的参数名
⑥ type: 类型(区分开关键字和封装类 int 和 Integer)
1.实体类的构造方法
2.applicationContext.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">
<!--id表示获取到对象标识
class创建那个类的对象
-->
<bean id="peo" class="com.ouc.pojo.People">
<constructor-arg index="0" name="id" type="int" value="123"></constructor-arg>
<constructor-arg index="1" name="name" type="java.lang.String" value="张三"></constructor-arg>
<constructor-arg index="2" name="age" type="int" value="66"></constructor-arg>
</bean>
</beans>
3.测试结果
2.实例工厂
(1)工厂设计模式:帮助创建类对象。一个工厂可以生产多个对象。
(2)实例工厂:需要先创建工厂,才能生产对象。
实现步骤:
(1)创建一个实例工厂
(2)在applicationContext.xml中配置工厂对象和需要创建的对象
(3)测试结果
3.静态工厂
不需要创建工厂,快速创建对象。
实现步骤:
(1)编写一个静态工厂在方法上添加static
(2)在applicationContext.xml中
(3)测试结果