Spring(二:IOC基于xml)

二、依赖注入

  • 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值