Spring的IOC

Spring的IOC

1 ioc的概念和作用
1、存哪去?
分析:由于我们是很多对象,肯定要找个集合来存。这时候有 Map 和 List 供选择。
到底选 Map 还是 List 就看我们有没有查找需求。有查找需求,选 Map。
所以我们的答案就是 在应用加载时,创建一个 Map,用于存放三层对象。
我们把这个 map 称之为容器。
2、还是没解释什么是工厂?
工厂就是负责给我们从容器中获取指定对象的类。这时候我们获取对象的方式发生了改变。
原来:
我们在获取对象时,都是采用 new 的方式。是主动的。如图所示:在这里插入图片描述
现在:
我们获取对象时,同时跟工厂要,有工厂为我们查找或者创建对象。是被动的。
这种被动接收的方式获取对象的思想就是控制反转,它是 spring 框架的核心之一。 如图所示:在这里插入图片描述
明确 ioc的作用:
削减计算机程序的耦合(解除我们代码中的依赖关系)。
2 spring基于XML的IOC环境搭建和入门
1.打开IDEA工具如图所示的界面,点击Create New Project。在这里插入图片描述
2.选择Maven工程和JDK的版本,如图所示:并点击Next。在这里插入图片描述
3.填写项目名称和保存的地址,点击Finish。如图所示:在这里插入图片描述
4.导入相应的依赖jar包的代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.txw</groupId>
    <artifactId>spring_03ioc</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--打包的方式-->
    <packaging>jar</packaging>
    <dependencies>
        <!--导入spring-context的依赖坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
    </dependencies>
</project>

5.编写账户的持久层接口代码如下:

package com.txw.dao;

/**
 * 账户的持久层接口
 */
@SuppressWarnings("all")    // 注解警告信息
public interface AccountDao {
    /**
     * 模拟保存账户
     */
    void saveAccount();
}

6.编写账户的持久层实现类代码如下:

package com.txw.dao.impl;

import com.txw.dao.AccountDao;
/**
 * 账户的持久层实现类
 */
@SuppressWarnings("all")    // 注解警告信息
public class AccountDaoImpl implements AccountDao {
    /**
     * 模拟保存账户
     */
    public  void saveAccount(){
        System.out.println("保存了账户");
    }
}

7.编写账户业务层的接口代码如下:

package com.txw.service;

/**
 * 账户业务层的接口
 */
@SuppressWarnings("all")    // 注解警告信息
public interface AccountService {
    /**
     * 模拟保存账户
     */
    void saveAccount();
}

8.编写账户业务层的接口实现类代码如下:

package com.txw.service.impl;

import com.txw.dao.AccountDao;
import com.txw.service.AccountService;
/**
 * 账户的业务层实现类
 */
@SuppressWarnings("all")    // 注解警告信息
public class AccountServiceImpl implements AccountService {
    // 声明AccountDao业务对象
    private AccountDao accountDao ;
    public AccountServiceImpl(){
        System.out.println("对象创建了");
    }
    public void  saveAccount(){
        accountDao.saveAccount();
    }
}

9.在resource目录下创建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
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--把对象的创建交给spring来管理-->
    <bean id="accountService" class="com.txw.service.impl.AccountServiceImpl"></bean>
    <bean id="accountDao" class="com.txw.dao.impl.AccountDaoImpl"></bean>
</beans>

10.编写测试的代码如下:

package com.txw.ui;

import com.txw.dao.AccountDao;
import com.txw.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

/**
 * 模拟一个表现层,用于调用业务层
 */
@SuppressWarnings("all")    // 注解警告信息
public class Client {
    /**
     * 获取spring的Ioc核心容器,并根据id获取对象
     * ApplicationContext的三个常用实现类:
     *      ClassPathXmlApplicationContext:它可以加载类路径下的配置文件,要求配置文件必须在类路径下。不在的话,加载不了。(更常用)
     *      FileSystemXmlApplicationContext:它可以加载磁盘任意路径下的配置文件(必须有访问权限)
     *      AnnotationConfigApplicationContext:它是用于读取注解创建容器的。
     *  ApplicationContext:     单例对象适用              采用此接口
     *      它在构建核心容器时,创建对象采取的策略是采用立即加载的方式。也就是说,只要一读取完配置文件马上就创建配置文件中配置的对象。
     *  BeanFactory:            多例对象使用
     *      它在构建核心容器时,创建对象采取的策略是采用延迟加载的方式。也就是说,什么时候根据id获取对象了,什么时候才真正的创建对象。
     * @param args
     */
    public static void main(String[] args) {
        // 1.获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//        ApplicationContext ac = new FileSystemXmlApplicationContext("C:\\Users\\Administrator\\Desktop\\bean.xml");
        // 2.根据id获取Bean对象
        AccountService as  = (AccountService)ac.getBean("accountService");
        AccountDao adao = ac.getBean("accountDao",AccountDao.class);
        System.out.println(as);
        System.out.println(adao);
        as.saveAccount();
        //--------BeanFactory----------
//        Resource resource = new ClassPathResource("bean.xml");
//        BeanFactory factory = new XmlBeanFactory(resource);
//        AccountService as  = (AccountService)factory.getBean("accountService");
//        System.out.println(as);
    }
}

选中ApplicationContext右键选择Diagrams,并点击Show Diagrams。如图所示:在这里插入图片描述
如图所示:继承关系图:在这里插入图片描述
选中ApplicationContext右键选择Show Implements,如图所示:在这里插入图片描述
它的实现类如图所示:在这里插入图片描述
3 spring中bean的细节之三种创建Bean对象的方式
1.打开IDEA工具如图所示的界面,点击Create New Project。在这里插入图片描述2.选择Maven工程和JDK的版本,如图所示:并点击Next。在这里插入图片描述
3.填写项目名称和保存的地址,点击Finish。如图所示:在这里插入图片描述
4.导入相应的依赖jar包的代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.txw</groupId>
    <artifactId>spring_04bean</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--打包的方式-->
    <packaging>jar</packaging>
    <dependencies>
        <!--导入的依赖jar包坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
    </dependencies>
</project>

5.编写账户业务层的接口代码如下:

package com.txw.service;

/**
 * 账户业务层的接口
 */
@SuppressWarnings("all")     // 注解警告信息
public interface IAccountService {
    /**
     * 模拟保存账户
     */
    void saveAccount();
}

6.编写账户的业务层实现类代码如下:

package com.txw.service.impl;

import com.txw.service.IAccountService;
/**
 * 账户的业务层实现类
 */
@SuppressWarnings("all")     // 注解警告信息
public class AccountServiceImpl implements IAccountService {
    public AccountServiceImpl(){
        System.out.println("对象创建了");
    }
    public void  saveAccount(){
        System.out.println("service中的saveAccount方法执行了。。。");
    }
    public void  init(){
        System.out.println("对象初始化了。。。");
    }
    public void  destroy(){
        System.out.println("对象销毁了。。。");
    }
}

7.在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
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--把对象的创建交给spring来管理-->
    <!--spring对bean的管理细节
        1.创建bean的三种方式
        2.bean对象的作用范围
        3.bean对象的生命周期
    -->
    <!--创建Bean的三种方式 -->
    <!-- 第一种方式:使用默认构造函数创建。
            在spring的配置文件中使用bean标签,配以id和class属性之后,且没有其他属性和标签时。
            采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建。
    <bean id="accountService" class="com.txw.service.impl.AccountServiceImpl"></bean>
    -->
    <!-- 第二种方式: 使用普通工厂中的方法创建对象(使用某个类中的方法创建对象,并存入spring容器)
    <bean id="instanceFactory" class="com.txw.factory.InstanceFactory"></bean>
    <bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>
    -->
    <!-- 第三种方式:使用工厂中的静态方法创建对象(使用某个类中的静态方法创建对象,并存入spring容器)
    <bean id="accountService" class="com.txw.factory.StaticFactory" factory-method="getAccountService"></bean>
    -->
    <!-- bean的作用范围调整
        bean标签的scope属性:
            作用:用于指定bean的作用范围
            取值: 常用的就是单例的和多例的
                singleton:单例的(默认值)
                prototype:多例的
                request:作用于web应用的请求范围
                session:作用于web应用的会话范围
                global-session:作用于集群环境的会话范围(全局会话范围),当不是集群环境时,它就是session
    <bean id="accountService" class="com.txw.service.impl.AccountServiceImpl" scope="prototype"></bean>
    -->
    <!-- bean对象的生命周期
            单例对象
                出生:当容器创建时对象出生
                活着:只要容器还在,对象一直活着
                死亡:容器销毁,对象消亡
                总结:单例对象的生命周期和容器相同
            多例对象
                出生:当我们使用对象时spring框架为我们创建
                活着:对象只要是在使用过程中就一直活着。
                死亡:当对象长时间不用,且没有别的对象引用时,由Java的垃圾回收器回收
     -->
    <bean id="accountService" class="com.txw.service.impl.AccountServiceImpl"
          scope="prototype" init-method="init" destroy-method="destroy"></bean>
</beans>

8.编写使用普通工厂中的方法创建对象(使用某个类中的方法创建对象,并存入spring容器)的代码如下:

package com.txw.factory;

import com.txw.service.IAccountService;
import com.txw.service.impl.AccountServiceImpl;
/**
 * 模拟一个工厂类(该类可能是存在于jar包中的,我们无法通过修改源码的方式来提供默认构造函数)
 */
@SuppressWarnings("all")     // 注解警告信息
public class InstanceFactory {
    public IAccountService getAccountService(){
        return new AccountServiceImpl();
    }
}

9.编写使用工厂中的静态方法创建对象(使用某个类中的静态方法创建对象,并存入spring容器)的代码如下:

package com.txw.factory;

import com.txw.service.IAccountService;
import com.txw.service.impl.AccountServiceImpl;
/**
 * 模拟一个工厂类(该类可能是存在于jar包中的,我们无法通过修改源码的方式来提供默认构造函数)
 */
@SuppressWarnings("all")     // 注解警告信息
public class StaticFactory {
    public static IAccountService getAccountService(){
        return new AccountServiceImpl();
    }
}

10.编写测试的代码如下:

package com.txw.ui;

import com.txw.service.IAccountService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * 模拟一个表现层,用于调用业务层
 */
@SuppressWarnings("all")     // 注解警告信息
public class Client {
    public static void main(String[] args) {
        // 1.获取核心容器对象
//        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        // 2.根据id获取Bean对象
        IAccountService as  = (IAccountService)ac.getBean("accountService");
        as.saveAccount();
        // 手动关闭容器
        ac.close();
    }
}

全局session,如图所示:Spring的IOC

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学无止路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值