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





posted on 2013-11-01 19:26 【村长】 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/qinyuan/p/3402646.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值