Spring中的IOC(二)--使用xml配置类的注入

一、前言说明

在上一篇的内容中,我们使用了一个自定义的工厂模式,通过Class.forName().newInstance()方法来创建管理我们的对象,接下来我们将通过spring框架来管理我们的对象;
还是原来的例子,我们建立一个普通的maven项目,该项目使用三层架构搭建一个基本框架;

二、框架的搭建

2.1项目框架如下:

使用IDEA自带的基架项目,建一个空的项目:

并导入spring的最核心坐标:

      <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>

2.2编写项目的内容

2.2.1 dao层

接口的定义

package org.study.dao;
public interface IAccountDao {
    void saveAccount();
}

实现类:

package org.study.dao.impl;
import org.study.dao.IAccountDao;
public class AccountDaoImpl implements IAccountDao {
    @Override
    public void saveAccount() {
        System.out.println("保存了...");
    }
}
2.2.2 service层

接口的定义

package org.study.service;
public interface IAccountService {
    void saveAccount();
}

实现类:

package org.study.service.impl;
import org.study.dao.IAccountDao;
import org.study.service.IAccountService;
public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao;
    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }
    @Override
    public void saveAccount() {
        accountDao.saveAccount();
    }
}
2.2.3 ui层,模拟用户的调用

模拟调用的代码

package org.study.ui;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.study.service.IAccountService;
import org.study.service.impl.AccountServiceImpl;
public class Client {
    public static void main(String[] args) {
        ApplicationContext context =new ClassPathXmlApplicationContext("bean.xml");
        IAccountService accountService = context.getBean("accountService",AccountServiceImpl.class);
        accountService.saveAccount();
    }
}

三、编写xml配置文件

3.1 bean.xml配置文件的编写

通过第二步,代码部分已经编写完毕,接下来我们需要使用spring来管理我们的类,并在我们需要使用时,通过ioc容器,可以获取到相应的类;
在resources文件夹下,编写bean.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="accountDao" class="org.study.dao.impl.AccountDaoImpl">
    </bean>

    <bean id="accountService" class="org.study.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>
</beans>

3.2 运行ui层中的方法,查看效果


可以看到,我们的代码正确运行了;

四、总结

1、引入spring框架的目的是帮助我们管理dao层、service层的类;在使用时,也可以通过spring容器来创建该类;
2、使用ApplicationContext类,来创建我们要使用的类,该类的具体实现是依赖于ClassPathXmlApplicationContext类来实现的;
3、使用xml配置我们要被管理的类时,要导入相应的约束;

原文地址:https://www.cnblogs.com/zqllove/p/13178115.html