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() {
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM