模拟一个保存账户的方法,在bean.xml中分别使用构造函数和set方法两种方式注入数据
使用构造函数时,sevice层的代码为
public class AccountServiceImpl implements AccountService {
private String name;
private Integer age;
public AccountServiceImpl(String name, Integer age) {
this.name = name;
this.age = age;
}
public void saveAccount() {
System.out.println("对象已保存"+ name +","+ age);
}
}
使用set方法注入时service层的代码为
public class AccountServiceImplSet implements AccountService {
private String name;
private Integer age;
private Date birthday;
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public void saveAccount() {
System.out.println("对象已保存"+ name +","+ age +","+ birthday);
}
bean.xml中的配置为
<!-- 第一种
使用默认构造函数
标签:constructor-arg
-->
<bean id="accountService" class="com.zwq.service.impl.AccountServiceImpl">
<constructor-arg name="name" value="小明"></constructor-arg>
<constructor-arg name="age" value="19"></constructor-arg>
</bean>
<!-- 设置一个日期对象 -->
<bean id="now" class="java.util.Date"></bean>
<!-- 第二种
set方法注入
标签:property
-->
<bean id="accountService2" class="com.zwq.service.impl.AccountServiceImplSet">
<property name="age" value="18"></property>
<property name="name" value="小红"></property>
<property name="birthday" ref="now"></property>
</bean>