IOC理论推导--控制反转
IOC推导
之前的业务模式
1.UserDao接口
2.UserDaolmpl 实现类
3.UserService 业务接口
4.UserServicelmpl 业务实现类
在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码!如果程序代码量十分大,修改一次的成本代价十分昂贵!
我们使用一个set接口实现,已经发生了革命性的变化
    //利用set进行动态实现值的注入
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
- 之前,程序是主动创建对象!控制权在程序猿手上!
- 使用了set注入后,程序不再具有主动性,而是变成了被动的接受对象!
这种思想,从本质上解决了问题,我们程序猿不用再去管理对象的创建了。系统的耦合性大大降低~
可以更加专注的在业务的实现上!|
IOC本质
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。
控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。没有IoC的程序中 , 我们使用面向对象编程 , 对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的.
反转∶程序本身不创建对象,而变成被动的接收对象﹒依赖注入:就是利用set方法来进行注入的.
IOC是一种编程思想,由主动的编程变成被动的接收.
可以通过newClassPathXmlApplicationContext去浏览一下底层源码﹒
OK,到了现在,我们彻底不用再程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的loC,一句话搞定:对象由Spring 来创建,管理,装配!
控制反转
resouces-----beans.xml

直接在beans配置对象,属性
<?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">
  <!--使用Spring来创建对象,在Spring这些都称谓Bean
    原本 类型 变量名 =new 类型();
    Hello hello = new Hello();
    Spring中
    id=变量名
    class = new的对象;
    property给属性设置
    -->
    <bean id="UserDaoImpl" class="com.liu.dao.UserDaoImpl"></bean>
    <bean id="UserDaoMysqlImpl" class="com.liu.dao.UserDaoMysqlImpl"></bean>
    <bean id="UserDaoOracleImpl" class="com.liu.dao.UserDaoOracleImpl"></bean>
    <bean id="UserServiceImpl" class="com.liu.service.UserServiceImpl">
        <!--ref:引用容器中创建好的对象-->
        <property name="userDao" ref="UserDaoOracleImpl"></property>
    </bean>
</beans>
test
import com.liu.dao.UserDaoMysqlImpl;
import com.liu.service.UserService;
import com.liu.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
    public static void main(String[] args) {
        //实际调用的是业务层,dao层用户不需要接触
        UserServiceImpl userService = new UserServiceImpl();
        userService.setUserDao(new UserDaoMysqlImpl());
        userService.getUser();
        //在beans.xml中注册号之后,直接获取ApplicationContext,上面的java代码可以直接不用
        //拿到Spring的容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        //我们的对象都在Spring中的管理里,要用就直接去取出来
        UserService userServiceImpl = (UserService) applicationContext.getBean("UserServiceImpl");
        userServiceImpl.getUser();
    }
}
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号