码迷,mamicode.com
首页 > 其他好文 > 详细

IoC(控制反转)和DI(依赖注入)

时间:2018-02-28 21:39:55      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:post   org   imp   src   http   getbean   XML   目标   com   

一、IOC

1.目标类

  • 提供UserService接口和实现类
  • 获得UserService实现类的实例

  之前开发中,直接new一个对象即可,使用spring之后,将由spring创建  --》IoC控制反转

以后需要实例对象时,从spring工厂(容器)获得,需要将实现类的全限定名称配置到xml中

技术分享图片

 

2.配置文件

 位置:任意,开发一般放在classpath下(src)

 名称:任意,一般使用applicationContext.xml

 内容:添加schema约束

 约束文件位置:spring-framework-3.2.0.RELEASE\docs\spring-framework-reference\html\xsd-config.html

<?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 definitions here 
    配置所需要创建的实例对象,放入spring容器中
    -->
    <bean class="service.UserServiceImp" id="userService"></bean>
</beans>

 

 3.测试

@Test
public void test01(){
    //获得容器
    String xmlPath = "service/beans.xml";
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
    //从容器中取实例对象
    UserService userService = (UserService) applicationContext.getBean("userService");
    System.out.println(userService);
    userService.addUser();
}

 二、DI

 1.目标类

技术分享图片

2.配置文件

<bean id="userService" class="DI.UserServiceImp">
    <!-- 属性注入,
        name:属性名,通过set方法获得
        ref:另一个bean的id的引用
     -->
    <property name="userDao" ref="userDao"></property>
</bean>
<bean id="userDao" class="DI.UserDaoImp"></bean>

 

 3.测试

@Test
public void test01(){
    //获得容器
    String xmlPath = "DI/beans.xml";
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
    //从容器中取实例对象
    UserService userService = (UserService) applicationContext.getBean("userService");
    System.out.println(userService);
    userService.addUser();
}

 

IoC(控制反转)和DI(依赖注入)

标签:post   org   imp   src   http   getbean   XML   目标   com   

原文地址:https://www.cnblogs.com/zhuxiang1633/p/8485635.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!