0三、DI依賴注入

DI(dependency Injection)---依賴注入
    什麼是依賴注入:
       經過給bean屬性注入值。注入的這個過程叫作依賴注入。PPT中解釋是DI:Dependency Injection 依賴注入,Spring框架負責建立Bean對象時,動態的將依賴對象注入到Bean組件。
 
代碼演示:
    beans.xml
  向service中的name屬性注入值。    
    <bean id="userService" class="cn.itcast.service.UserService">
        <property name="name" value="張三"></property>
    </bean>
UserService.java
package cn.itcast.service;
/*
 * 表明業務層組建
 * */
public class UserService {
    private String name;
    /*
     * 模擬保存操做
     * */
    public void save(){
        System.out.println("保存用戶..."+name);
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
SpringTest.java
package test;
 
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import cn.itcast.service.UserService;
 
public class SpringTest {
    //測試spring工廠
    @Test
    public void test(){
        //將UserService對象的建立交給spring。直接從spring工廠中獲取
        //讀取spring配置文件建立spring工廠
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        //從工廠中獲取對象
        UserService us = (UserService) ctx.getBean("userService");
        us.save();
    }
}



相關文章
相關標籤/搜索