IoC基础例子

一个简单的例子:

一般新建一个com.dao包,存放一些dao接口。

com.dao.impl里面存放具体的dao

com.service存放service接口

com.service.impl具体的service

serviceImpl里面定义一个dao的对象,使用service的对应方法调用到dao的对应方法

接口的定义是因为java中推荐使用接口编程

<?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 id="dog" class="com.Model.Dog" >
        <constructor-arg index="0" value="阿旺"></constructor-arg>
        <constructor-arg index="1" value="5"></constructor-arg>
    </bean>
    --><bean id="idaoImpl" class="com.dao.impl.IDaoImpl"></bean>
    <bean id="serviceImpl" class="com.service.impl.ServiceImpl">
        <property name="dao" ref="idaoImpl"></property>
    </bean>
</beans>

使用applicationContext对象获取bean容器中的实例化对象

            ApplicationContext ac=
                new ClassPathXmlApplicationContext("com/test/applicationContext.xml");
            IService hello=(IService) ac.getBean("serviceImpl");

 

Service、DAO层是作为独立的组件出现的。在编码阶段,即没有实例化对象,也没有设置依赖关系,而是把它交给Spring,由Spring在运行阶段实例化、组装对象,然后一步步执行的做法,因此被称为反向控制,或者反转控制。

spring在运行阶段会把所有的bean实例化,所以不需要的在构造方法中的输出可以省去,免得。。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值