zoukankan      html  css  js  c++  java
  • 对象类型的属性注入

    ---------------------siwuxie095

       

       

       

       

       

       

       

    对象类型的属性注入

       

       

    1、应用场景:在 Service 类中得到 Dao 类的对象

       

       

       

       

    2、具体步骤

       

    (1)在 Service 中把 Dao 作为类型属性

       

    (2)提供 Dao 类型属性的 set 方法

       

       

       

       

    3、具体实现

       

    1)编写一个 Dao 类

       

    Dao.java:

       

    package com.siwuxie095.ioc;

       

    public class Dao {

    public void add() {

    System.out.println("----- Dao -----");

    }

    }

       

       

       

    2)编写一个 Service 类

       

    Service.java:

       

    package com.siwuxie095.ioc;

       

    public class Service {

     

    private Dao dao;

     

    public void setDao(Dao dao) {

    this.dao = dao;

    }

     

    public void add() {

    System.out.println("----- Service -----");

    dao.add();

    }

     

    }

       

       

       

    3)在配置文件中注入属性

       

    applicationContext.xml:

       

    <?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="daox" class="com.siwuxie095.ioc.Dao"></bean>

     

     

    <bean id="service" class="com.siwuxie095.ioc.Service">

     

    <!-- ref 属性即为要注入的对象 -->

    <property name="dao" ref="daox"></property>

     

    </bean>

     

       

    </beans>

       

       

       

    4)编写一个测试类

       

    TestIoc.java:

       

    package com.siwuxie095.ioc;

       

    import org.junit.Test;

    import org.springframework.context.ApplicationContext;

    import org.springframework.context.support.ClassPathXmlApplicationContext;

       

    public class TestIoc {

       

    /**

    * 手动加上 @Test 以进行单元测试(将自动导入 JUnit 4 jar 包)

    *

    * 选中方法名,右键->Run As->JUint Test

    */

    @Test

    public void testIoc(){

     

    // (1) 加载 Spring 的核心配置文件

    ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");

     

    // (2) 得到核心配置文件中创建的对象(获取 Bean 实例)

    Service service=(Service) context.getBean("service");

     

    service.add();

    }

    }

       

       

       

       

       

       

       

       

       

    【made by siwuxie095】

  • 相关阅读:
    ES6/ES2015核心内容(上)
    集合转数组的toArray()和toArray(T[] a)方法
    重复输出一个给定的字符串
    10道典型的JavaScript面试题
    用 JavaScript 检测浏览器在线/离线状态(JavaScript API — navigator.onLine)
    List<实体>与List<String>数据互转
    CSS实现四种loading动画效果
    Windows上安装Mac OS
    Android应用层View绘制流程之measure,layout,draw三步曲
    推断输入信息是否为空
  • 原文地址:https://www.cnblogs.com/siwuxie095/p/7402632.html
Copyright © 2011-2022 走看看