二、依赖注入
- DI: Dependency Injection
1. 构造函数
- 调用有参构造器创建对象
- 基础数据类型和String类型
- 其他bean类型
- 一般集合类型不会用这种方式来进行构建
bean.xml
<bean id="accountService" class="service.AccountServiceImpl">
<!--优势: 必须为所有的参数进行赋值,否则bean对象无法创建成功-->
<!--name:指定构造函数中参数名字-->
<!--value:基本数据类型的赋值-->
<!--ref: 其他应用类型bean的赋值-->
<constructor-arg name="age" value="18"></constructor-arg>
<constructor-arg name="name" value="shuzhan"></constructor-arg>
<constructor-arg name="birthDay" ref="now"></constructor-arg>
</bean>
<bean id = "now" class="java.util.Date"></bean>
bean对象
package service;
public class AccountServiceImpl{
// 如果经常变化的数据,并不适合注入的方式
private String name;
private Integer age;
private Date birthDay;
public AccountServiceImpl(String name, Integer age, Date birthDay) {
this.name = name;
this.age = age;
this.birthDay = birthDay;
}
}
2. set方法
- 调用无参构造创建bean对象
- 基础数据类型和String类型
- 其他bean类型
bean.xml
<bean id="accountDao" class="dao.AccountDaoImpl" >
<!--优势: 不必为所有参数都进行设置,但不保证所有的参数都能赋值-->
<!--更常用的注入方式-->
<property name="name" value="zhangsan"></property>
<property name="age" value="20"></property>
<property name="birthDay" ref="now"></property>
</bean>
<bean id = "now" class="java.util.Date"></bean>
bean对象
package dao;
@Setter
public class AccountDaoImpl {
private String name;
private Integer age;
private Date birthDay;
}