[刘阳Java]_Spring IOC程序代码如何编写_第3讲

第2讲我们介绍了Spring IOC的基本原理,这篇文章告诉大家Spring IOC程序代码是如何编写的,从而可以更好的理解IOC和DI的概念(所有的Java类的初始化工作扔给Spring框架,一个Java类如果依赖其他Java类,则此类依赖另一个Java类的初始化工作也扔给Spring框架来完成

下面我们通过在MVC开发中业务逻辑层和Dao层之间的关系来讲解利用Spring IOC和DI来实现依赖注入的关系

 1. 创建一个业务逻辑层的类(先声明一下这里的业务逻辑层我们就没有再去定义接口,所以业务逻辑层的实现类就是一个普通的Java类),PetServiceImpl。此类需要依赖于两个Dao层对象

package com.gxa.spring.day01;

public class PetServiceImpl {
    
    private PetDaoImplpetDao; //依赖对象
    private ItemDaoImplitemDao; //依赖对象
    
    public void setPetDao(PetDaoImplpetDao) {
        this.petDao = petDao;
    }
    
    public void setItemDao(ItemDaoImplitemDao) {
        this.itemDao = itemDao;
    }
    
    public void selectPet() {
        petDao.selectPet();
        itemDao.selectItem();
    }
}

2. 我们再创建两个Dao层的类(这里我们也再声明一下Dao层的也没有定义接口,只是一个普通的Java类),PetDaoImpl和ItemDaoImpl

package com.gxa.spring.day01;

public class PetDaoImpl {
    
    public void selectPet() {
        /**
         * 完成宠物数据查询
         */
        System.out.println("==宠物数据查询==");
    }
}
package com.gxa.spring.day01;

public class ItemDaoImpl {
    
    public void selectItem() {
        /**
         * 完成宠物分类数据查询
         */
        System.out.println("==宠物分类的数据查询==");
    }
}

大家注意一下PetServiceImpl中的两个Dao类,我们并没有在PetServiceImpl类使用new关键字来初始化。而是分别给PetDaoImpl和ItemDaoImpl追加两个setter方法。这两个setter方法非常关键,Spring框架就是通过setter方法来代替PetServiceImpl类给两个Dao层的类进行初始化的

3. 编写一个Spring的配置文件,将PetServiceImpl, PetDaoImpl, ItemDaoImpl 注入到 Spring框架中。同时还配置了PetServiceImpl的依赖关系(DI)

<?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="person" class="com.gxa.spring.day01.Person"></bean>
    
    <bean id="petService" class="com.gxa.spring.day01.PetServiceImpl">
        <property name="petDao" ref="petDao"></property>
        <property name="itemDao" ref="itemDao"></property>
    </bean>
    
    <bean id="petDao" class="com.gxa.spring.day01.PetDaoImpl"></bean>
    
    <bean id="itemDao" class="com.gxa.spring.day01.ItemDaoImpl"></bean>
</beans>

注意上面的<bean id="petService" .../>中的<property .../>,此标签就是在给PetServiceImpl设置依赖关系

4. 编写一个测试类

package com.gxa.spring.test01;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.gxa.spring.day01.Person;
import com.gxa.spring.day01.PetServiceImpl;

public class Test01 {
    
    @Test
    public void m02() {
        BeanFactorybeanFactory = new ClassPathXmlApplicationContext("spring.xml");
        PetServiceImplpetService = (PetServiceImpl) beanFactory.getBean("petService");
        petService.selectPet();
    }
}
原文地址:https://www.cnblogs.com/liuyangjava/p/6656935.html