IOC的中文翻译是控制反转,inversing of control .意思是在代码编写中,把 部分 创建对象 的功能交给框架。
原因是在软件工程实践中,人们发现当在代码中需要频繁创建某个对象时,例如java Web中servlet层需要调用service层的接口实现类方法,那首先就要在代码中获得一个接口实现类的对象。
例如
StudentLoginService studentLoginService = new StudentLoginServiceImpl();//创建sercive对象 Student student = studentLoginService.studentLogin(name, address);//调用service层对象方法
对象studentLoginService是接口型的,因为可以对应不同的实现类,从而具有灵活性。
但是在代码中用new 方式创建对象,如果后期需要用不同的实现类来替换升级,而这样的代码块有很多的话,例如1万个,就会出现更新困难的问题——手动修改1万个代码块,心里无数个神兽。
控制反转的意思,就是spring这样的框架,他帮你实现了一个功能,你只需要告诉它(通过xml配置文件)你需要创建的对象的路径(包名),它就能利用java反射技术,帮你创建对象,并且在一个容器(类似map)中保存。
这样当有新的实现类的时候,就不需要再在代码块中修改new 语句,只需要修改xml配置文件中对象类的路径,框架就可以帮你用新的类创建对象。
上面的代码就可以修改成这样:
private StudentLoginService studentLoginService;//声明类属性
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); studentLoginService = (StudentLoginService) ac.getBean("studentLoginService");
Student student = studentLoginService.studentLogin(name, address);调用service方法
在xml文件中:
<!-- serviceimpl对象bean--> <bean id="studentLoginService" class="com.tugou.run.service.impl.StudentLoginServiceImpl"> <property name="studentMapper" ref="studentMapper"/> </bean>