Spring IOC 为 MVC 解耦项目前期准备

上周写了两篇关于MVC解耦的文章,其实在 Spring 全家桶中,spring ioc 同样也是为解耦而存在,那我们就一步步的改造这个项目吧。

  • 文章传送门:

工厂模式为 MVC 解耦实战

工厂模式 + 单例模式实战

创建项目

项目创建选择的是 Maven 项目,因为可以自动导入 SpringFramework 的包。

  • 创建好之后长这样:

创建maven项目

导入模拟登录源码

进入模拟登录项目把 java 包下的全部复制黏贴到创建好的项目的 Java 包下便可。

  • 黏贴好之后是这样的:

importLoginDemo

配置 Spring 依赖

这一步尤为重要,仓库拉取出错,可能是仓库需要换成国内的源。

  • 在项目的根目录下的 pom.xml 中添加 spring 依赖,等待拉取完成便可。
<dependencies>
    <!-- springframework 依赖 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.3.RELEASE</version>
    </dependency>

</dependencies>
  • 还需要添加配置文件,在 resource 包下,新建文件,命名为 bean.xml,并向里面添加以下代码:

add bean.xml file

  • 然后配置 bean ,详细看代码:
<?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-3.0.xsd">
    <!--    把对象的创建交给 spring 来管理-->
    <bean id="accountService" class="wiki.laona.service.impl.AccountServiceImpl"/>

    <bean id="accountDao" class="wiki.laona.dao.impl.AccountDaoImpl"/>
</beans>

测试

前面完成了准备工作,现在测试下项目是否搭建成功,这里需要改一下 AccountDemo 的代码。

  • 通过 ApplicationContext 获取配置项目路径,
public class AccountDemo {

    /**
     * 获取 spring 的 IOC 的核心容器,并根据 is 获取对象
     * @param args
     */
    public static void main(String[] args) {
//        IAccountService as = new AccountServiceImpl();
        // 获取核心容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        // 根据 id 获取 bean 对象
        IAccountService as = (IAccountService) applicationContext.getBean("accountService");
        IAccountDao ad = applicationContext.getBean("accountDao", IAccountDao.class);
        // 打印内存地址
        System.out.println(as);
        System.out.println(as);
        System.out.println(as);
        System.out.println(ad);
        System.out.println(ad);
        System.out.println(ad);
        // 保存账号
        as.saveAccount();
    }
}
  • 打印结果如下:
wiki.laona.service.impl.AccountServiceImpl@343f4d3d
wiki.laona.service.impl.AccountServiceImpl@343f4d3d
wiki.laona.service.impl.AccountServiceImpl@343f4d3d
wiki.laona.dao.impl.AccountDaoImpl@53b32d7
wiki.laona.dao.impl.AccountDaoImpl@53b32d7
wiki.laona.dao.impl.AccountDaoImpl@53b32d7
已保存账户

Process finished with exit code 0

好了,毛问题,完事。

小结

其实这里的项目前期准备,只是把之前的工厂模式中的实现方式换成了通过spring 的 ApplicationContext 获取实例对象。但是整个项目就换成了最流行的 spring 架构,听起来比较高大上。


人若无名,专心练剑~!

猜你喜欢

转载自www.cnblogs.com/huaiangg/p/12508284.html