Spring依赖注入 set方法注入

涉及的标签:property

标签的属性:

  name:用于指定注入时所调用的set方法的名称(注意name的值是set方法的名字小写)

  value:用于提供基本数据类型和String类型的数据

  ref:用于指定其他的bean。它的值就是在spring的Ioc核心容器中出现过的bean对象

 

优势:创建对象是时没有明确的要求,可以直接使用默认的构造函数

弊端:如果有某个成员必须有值,则获取对象时有可能set方法没有执行

<bean id="accountService" class="com.xuefei.service.impl.AccountServiceImpl">
        <property name="name" value="小王"></property>
        <property name="age" value="22"></property>
        <property name="date" ref="now"></property>
    </bean>
    <bean id="now" class="java.util.Date"></bean>
package com.xuefei.service.impl;

import com.xuefei.service.AccountService;

import java.util.Date;

/**
 * 账户业务层实现类
 */
public class AccountServiceImpl implements AccountService {

    String name;
    Integer age;
    Date date;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void setDate(Date date) {
        this.date = date;
    }
    public void say() {
        System.out.println("我是"+name+"今年"+age+"岁了!"+date);
    }

    public void saveAccount() {
    }
}

猜你喜欢

转载自www.cnblogs.com/lililixuefei/p/11874850.html