什么是Spring的IOC?

IOC:Inversion of Control   控制反转

原来创建对象程序员可以通过new的方式创建。

Spring框架是一个组件管理框架,可以将创建对象的权力交给spring。spring就像一个容器,需要对象,直接找它拿就行。

怎么进行控制反转?

1.spring.xml中的配置方式

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean class="di.DeptDAOImpl" id="deptDAO"></bean>
<!--    class=“填写需要托管给spring的类”   id="相当于这个类在spring框架中的唯一标识"-->
    <bean class="di.DeptServiceImpl" id="deptService">
        <property name="deptDAO" ref="deptDAO"></property>
<!--    property name="这个填的是DeptServiceImpl中依赖的那个deptDAO变量" ref="这里填依赖的那个变量是spring中的什么类型,填该类的id号"></property    -->
<!--        通过property就可以进行依赖注入了,当然要给注入的类型,设置一个私有变量和公有的set方法-->
    </bean>
</beans>

2.被DAO注入的Service,这里DAO不要new了,因为已经托管给spring了,而且也通过property使两个类产生依赖关系

package di;

public class DeptServiceImpl implements DeptService{
    private DeptDAO deptDAO;

    public void setDeptDAO(DeptDAO deptDAO) {
        this.deptDAO = deptDAO;
    }

    @Override
    public void save(String name) {
        System.out.println("deptService name = " + name);
        deptDAO.save("hhhhh");
    }
}

3.DAO

package di;

public class DeptDAOImpl implements DeptDAO {
    @Override
    public void save(String name) {
        System.out.println("姓名 = " + name);
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值