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实例化,所以不需要的在构造方法中的输出可以省去,免得。。。