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



相关文章
相关标签/搜索