Spring01:概述、工厂模式解耦、Spring中的IOC

  • 四天课程安排
    • 第一天:Spring框架的概述、Spring中基于XML的IOC配置
    • 第二天: Spring中基于注解的IOC和IOC的案例(单表增删改查,持久层随意)
    • 第三天:Spring中的AOP和基于XML以及注解的AOP配置
    • 第四天:Spring中的JDBCTemplate及Spring事务控制
  • 今日内容
    • Spring的概述
      • Spring是什么
      • Spring的两大核心--AOC和IOP
      • Spring的发展历程和优势
      • Spring的体系结构
    • 程序的耦合及解耦
      • 以往案例中的问题
      • 工厂模式解耦
    • IOC的概念和Spring中的IOC
      • Spring中基于xml的IOC环境搭建
    • 依赖注入(Dependency Injection,DI)
    • 作业:
一、Spring的概述
1、概述--spring.io
Spring 是分层的 Java SE/EE 应用 full-stack 轻量级开源框架,以 IoC(Inverse Of Control:
反转控制)和 AOP(Aspect Oriented Programming:面向切面编程)为内核,提供了展现层 Spring 
MVC 和持久层 Spring JDBC 以及业务层事务管理等众多的企业级应用技术,还能整合开源世界众多
著名的第三方框架和类库,逐渐成为使用最多的 Java EE 企业应用开源框架。
三层架构
2、Spring的发展历程
3、Spring的优势
  • 解耦:今天、明天
  • AOP面向切面编程:Aspect Oriented Programming第三天
  • 声明式事务:第四天
  • 方便程序的测试:第二天
  • 方便集成各种优秀框架:第三天的ssm整合
  • 降低JavaEE API的使用难度:第四天的JDBC、Spring和JavaMail的整合
  • Java源码是经典学习范例
4、spring的体系结构
  • Mybatis基于maven工程进行构建
  • 官网有maven的坐标
  • 资料提供源码dist、文档docs、约束scheme
1 2 4均需要核心容器的支持
二、程序的耦合及解耦
1、编写jdbc的工程代码用于分析程序的耦合
package com.itheima.jdbc;

import java.sql.*;

/**
 * 程序的耦合
 */
public class JdbcDemo1 {
    public static void main(String[] args) throws Exception {
        //1.注册驱动
        //不导包,没有依赖会产生编译器异常
        //没有MySQL驱动就无法编译
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        //2.获取连接
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/eesy_spring","root","root");
        //3.获取操作数据库的预处理对象
        PreparedStatement pstm = connection.prepareStatement("select * from account");
        //4.执行SQL,得到结果集
        ResultSet rs = pstm.executeQuery();
        //5.遍历结果集
        while(rs.next()){
            System.out.println(rs.getString("name"));
        }
        //6.释放资源
        rs.close();
        pstm.close();
        connection.close();
    }
}
2、程序的耦合和解耦的思路分析1
  • 耦合:程序间的依赖关系,包括
    • 类之间的依赖
    • 方法间的依赖
  • 解耦:降低程序间的依赖关系
  • 实际开发中应该做到:
    • 编译期不依赖
    • 运行时才依赖
  • 解耦的思路:
    • 第一步:使用反射创建对象(只依赖于字符串,而不依赖于驱动类),而避免使用new关键字
      • 缺点Class.forName("com.mysql.jdbc.Driver");更换为其他数据库时太麻烦
    • 第二步:通过读取配置文件获取要创建的对象的全限定类名
  • 需要解决:表现层调业务层、业务层调持久层,使代码的独立性很差
3、编写工厂类和配置文件
Bean.properties
accountService=com.itheima.service.impl.AccountServiceImpl
accountDao=com.itheima.dao.impl.AccountDaoImpl
package com.itheima.factory;
/**
 * 一个创建Bean对象的工厂
 *
 * Bean:在计算机英语中,有可重用组件的含义
 * Java Bean:用Java语言编写的可重用组件
 *      容易看成实体类,实际上不相等,>
 * 它就是用于创建service和dao对象的
 *
 * 第一个:需要一个配置文件来配置service和dao
*        配置的内容:唯一标识=全限定类名(key=value)
 * 第二个:通过读取配置文件中配置的内容,反射创建对象
 *
 * 配置文件可以使xml或properties(配置结构更简单)
 */
public class BeanFactory {
}
4、工厂模式解耦
package com.itheima.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 一个创建Bean对象的工厂
 *
 * Bean:在计算机英语中,有可重用组件的含义
 * Java Bean:用Java语言编写的可重用组件
 *      容易看成实体类,实际上不相等,>
 * 它就是用于创建service和dao对象的
 *
 * 第一个:需要一个配置文件来配置service和dao
*        配置的内容:唯一标识=全限定类名(key=value)
 * 第二个:通过读取配置文件中配置的内容,反射创建对象
 *
 * 配置文件可以使xml或properties(配置结构更简单)
 */
public class BeanFactory {
    //定义一个Properties对象
    private static Properties props;
    //使用静态代码块为Properties对象赋值
    static{
        try {
            //实例化对象
            props = new Properties();
            //获取properties的流对象
            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("Bean.properties");
            props.load(in);
        } catch (IOException e) {
            throw new ExceptionInInitializerError("初始化properties失败");
        }
    }

    /**
     * 根据Bean的名称获取bean对象
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName){
        Object bean = null;
        try {
            String beanPath = props.getProperty(beanName);
            System.out.println(beanPath);
            //反射
            bean = Class.forName(beanPath).newInstance();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }
}
package com.itheima.ui;

import com.itheima.factory.BeanFactory;
import com.itheima.service.IAccountService;
import com.itheima.service.impl.AccountServiceImpl;

/**
 * 模拟一个表现层,用于调用业务层
 */
public class Client {

    public static void main(String[] args) {
        //IAccountService as = new AccountServiceImpl();
        IAccountService as = (IAccountService)BeanFactory.getBean("accountService");
        as.saveAccount();
    }
}
package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.dao.impl.AccountDaoImpl;
import com.itheima.factory.BeanFactory;
import com.itheima.service.IAccountService;

/**
 * 账户的业务层实现类
 */
public class AccountServiceImpl implements IAccountService {
    //业务层调用持久层
    //避免写new
    //private IAccountDao accountDao = new AccountDaoImpl();
    private IAccountDao accountDao = (IAccountDao)BeanFactory.getBean("accountDao");
    @Override
    public void saveAccount() {
        accountDao.saveAccount();
    }
}
5、分析工厂模式中的问题并改造
  • 打印五次有五次实例(多例对象)
  • 单例:只有一个实例;【推荐】将成员变量放到方法内部,即可实现变量每次的初始化
6、工厂模式解耦的升级版
package com.itheima.factory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
 * 一个创建Bean对象的工厂
 *
 * Bean:在计算机英语中,有可重用组件的含义
 * Java Bean:用Java语言编写的可重用组件
 *      容易看成实体类,实际上不相等,>
 * 它就是用于创建service和dao对象的
 *
 * 第一个:需要一个配置文件来配置service和dao
*        配置的内容:唯一标识=全限定类名(key=value)
 * 第二个:通过读取配置文件中配置的内容,反射创建对象
 *
 * 配置文件可以使xml或properties(配置结构更简单)
 */
public class BeanFactory {
    //定义一个Properties对象
    private static Properties props;
    //定义一个map,用于存放创建的对象,我们将其称之为容器
    private static Map<String,Object> beans;
    //使用静态代码块为Properties对象赋值
    static{
        try {
            //实例化对象
            props = new Properties();
            //获取properties的流对象
            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("Bean.properties");
            props.load(in);
            //实例化容器
            beans = new HashMap<>();
            //取出配置文件中所有的key
            Enumeration keys = props.keys();
            //遍历枚举
            while(keys.hasMoreElements()){
                //取出每个key
                String key = keys.nextElement().toString();
                //根据key获取value
                String beanPath = props.getProperty(key);
                //反射创建对象
                Object value = Class.forName(beanPath).newInstance();
                //把key和value存入容器之中
                beans.put(key,value);
            }
        } catch (Exception e) {
            throw new ExceptionInInitializerError("初始化properties失败");
        }
    }
    /**
     * 根据Bean的名称获取bean对象
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName){
       return beans.get(beanName);
    }
}
package com.itheima.ui;
import com.itheima.dao.IAccountDao;
import com.itheima.factory.BeanFactory;
import com.itheima.service.IAccountService;
import com.itheima.service.impl.AccountServiceImpl;

/**
 * 模拟一个表现层,用于调用业务层
 */
public class Client {
    private IAccountDao accountDao = (IAccountDao)BeanFactory.getBean("accountDao");
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            IAccountService as = (IAccountService)BeanFactory.getBean("accountService");
            System.out.println(as);
            as.saveAccount();
        }
    }
}
package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.dao.impl.AccountDaoImpl;
import com.itheima.factory.BeanFactory;
import com.itheima.service.IAccountService;

/**
 * 账户的业务层实现类
 */
public class AccountServiceImpl implements IAccountService {
    //业务层调用持久层
    //避免写new
    //private IAccountDao accountDao = new AccountDaoImpl();
    private IAccountDao accountDao;
    //private int i = 1;
    public void saveAccount() {
        accountDao = (IAccountDao)BeanFactory.getBean("accountDao");
        int i = 1;
        //如果想每次调用得到的是新值,则需要定义到方法内部
        accountDao.saveAccount();
        System.out.println(i);
        i++;
    }
}
三、IOC的概念和Spring中的IOC
1、ioc的概念和作用
Inversion of Control
两种创建对象的方式
private IAccountDao accountDao = new AccountDaoImpl();
private IAccountDao accountDao = (IAccountDao)BeanFactory.getBean("accountDao");
主动new对象:
控制反转,被动接收
对象创建的控制权被动转移给工厂,削减程序的耦合
2、spring中的Ioc前期准备
作用:解决程序间的依赖关系,解耦
3、spring基于XML的IOC环境搭建和入门
<?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.itheima.service.impl.AccountServiceImpl"></bean>
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"></bean>
</beans>
package com.itheima.ui;
import com.itheima.dao.IAccountDao;
import com.itheima.service.IAccountService;
import com.itheima.service.impl.AccountServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 *
 */
public class Client {
    /**
     * 获取Spring的IOC核心容器,并根据id获取对象
     * @param args
     */
    public static void main(String[] args) {
        //1.获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象---两种方式
        IAccountService as = (IAccountService) ac.getBean("accountService");
        IAccountDao adao = ac.getBean("accountDao",IAccountDao.class);
        System.out.println(as);
        System.out.println(adao);
    }
}
4、ApplicationContext的三个实现类
如何找到接口的实现类
 * Application的三个常用实现类
     *      ClassPathXmlApplicationContext:可以加载类路径下的配置文件,要求配置文件必须在类路径下,不在的加载不了【更常用】
     *      FileSystemApplicationContext:可以加载磁盘任意路径下的配置文件(必须有访问权限)
    *       ※ new FileSystemXmlApplicationContext ("D:\\IdeaProjects\\06Spring\\day03_eesy_03Spring \\src\\main\\resources\\bean.xml");
     *      AnnotationConfigApplicationContext:是用于读取注解创建容器的,为明天的内容
5、BeanFactory和ApplicationContext的区别【创建的时间不同:立即加载和延迟加载】
package com.itheima.ui;
import com.itheima.dao.IAccountDao;
import com.itheima.service.IAccountService;
import com.itheima.service.impl.AccountServiceImpl;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
/**
 *
 */
public class Client {
    /**
     * 获取Spring的IOC核心容器,并根据id获取对象
     * Application的三个常用实现类
     *      ClassPathXmlApplicationContext:可以加载类路径下的配置文件,要求配置文件必须在类路径下,不在的加载不了
     *      FileSystemApplicationContext:可以加载磁盘任意路径下的配置文件(必须有访问权限)
     *      AnnotationConfigApplicationContext:是用于读取注解创建容器的,为明天的内容
     * @param args
     */
    public static void main(String[] args) {
/*        //1.获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象---两种方式
        IAccountService as = (IAccountService) ac.getBean("accountService");
        IAccountDao adao = ac.getBean("accountDao",IAccountDao.class);
        System.out.println(as);
        System.out.println(adao);*/
        //***---BeanFactory***///
        Resource resource = new ClassPathResource("bean.xml");
        BeanFactory factory = new XmlBeanFactory(resource);
        IAccountService as = (IAccountService) factory.getBean("accountService");
        IAccountDao adao = factory.getBean("accountDao",IAccountDao.class);
        System.out.println(as);
        System.out.println(adao);
    }
}
核心容器的两个接口引发出的问题
  • ApplicationContext:在构建核心容器时,创建对象采取的策略是立即加载的方式;即只要一读取完配置文件,马上就创建配置文件中配置的对象【单例对象适用】※常用此接口定义容器对象
  • 类视图找到的BeanFactory:在构建核心容器时,创建对象采取的策略是延迟加载的方式。也就是说,什么时候根据id读取对象了,什么时候才真正创建对象。【多例对象适用】【顶层接口】
6、spring中bean的细节之三种创建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.xsd">
    <!--把对象的创建交给Spring管理-->
    <!--
    Spring对Bean的管理细节
        1、创建Bean的三种方式
        2、Bean对象的作用范围
        3、Bean对象的生命周期
        -->
    <!--创建Bean的三种方式-->
    <!--第一种方式:使用默认构造函数创建
        在Spring的配置文件中使用bean标签 ,配以id和class属性后,且没有其他属性和标签时
        采用的就是默认构造函数创建Bean对象,此时如果没有构造函数,则对象无法创建
        -->
    <!--<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>-->
    <!--jar中只有class文件,获取有些对象的返回值,则需要采用第二种或第三种创建对象-->
    <!--第二种方式:使用普通工厂中的方法创建对象(使用类中的方法创建对象,并存入Spring容器)-->
    <bean id="instanceFactory" class="com.itheima.factory.InstancsFactory"></bean>
    <bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>

    <!--第三种方式:使用静态工厂中的静态方法创建对象,并存入Spring容器-->
<!--
    <bean id="accountService" class="com.itheima.factory.StaticFactory" factory-method="getAccountService"></bean>
-->

</beans>
package com.itheima.ui;
import com.itheima.service.IAccountService;
import com.itheima.service.impl.AccountServiceImpl;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/**
 *
 */
public class Client {
    /**
     * 获取Spring的IOC核心容器,并根据id获取对象
     * @param args
     */
    public static void main(String[] args) {
        //1.获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象---两种方式
        IAccountService as = (IAccountService) ac.getBean("accountService");
        System.out.println(as);
        as.saveAccount();
    }
}
7、spring中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.xsd">
    <!--bean的作用范围调整
        默认是单例
        通过bean标签的scope属性,调整bean的作用范围
        取值:(单例和多例最常用)
            singleton:单例的(默认值)
            prototype:多例的
            request:作用于web应用的请求范围
            session:作用于web应用的会话范围
            global-session:作用于集群环境的全局会话范围,当不是集群环境时,就是session
    -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl" scope="prototype"></bean>
</beans>
8、spring中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.xsd">
    <!--把对象的创建交给Spring管理-->
    <!--
    Spring对Bean的管理细节
        1、创建Bean的三种方式
        2、Bean对象的作用范围
        3、Bean对象的生命周期
        -->
    <!--创建Bean的三种方式-->
    <!--第一种方式:使用默认构造函数创建
        在Spring的配置文件中使用bean标签 ,配以id和class属性后,且没有其他属性和标签时
        采用的就是默认构造函数创建Bean对象,此时如果没有构造函数,则对象无法创建
        -->
    <!--<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>-->
    <!--jar中只有class文件,获取有些对象的返回值,则需要采用第二种或第三种创建对象-->
    <!--第二种方式:使用普通工厂中的方法创建对象(使用类中的方法创建对象,并存入Spring容器)-->
    <!--<bean id="instanceFactory" class="com.itheima.factory.InstancsFactory"></bean>
    <bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>-->

    <!--第三种方式:使用静态工厂中的静态方法创建对象,并存入Spring容器-->
<!--
    <bean id="accountService" class="com.itheima.factory.StaticFactory" factory-method="getAccountService"></bean>
-->
    <!--bean的作用范围调整
        默认是单例
        通过bean标签的scope属性,调整bean的作用范围
        取值:(单例和多例最常用)
            singleton:单例的(默认值)
            prototype:多例的
            request:作用于web应用的请求范围
            session:作用于web应用的会话范围
            global-session:作用于集群环境的全局会话范围,当不是集群环境时,就是session
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl" scope="prototype"></bean>
    -->
    <!--bean对象的生命周期
        区分单例对象/多例对象
        单例对象
            出生:当容器创建时,对象出生
            存活:只要容器还在,对象就一直活着
            死亡:容器销毁,对象消亡
            总结:单例对象的生命周期和容器相同
        多例对象
            出生:当使用对象时,Spring框架为我们创建
            存活:对象在使用过程中一直存活
            死亡:当对象长时间不用且没有其他对象引用时,由Java的垃圾回收期回收
    -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl" scope="prototype"
    init-method="init" destroy-method="destroy"></bean>

</beans>
package com.itheima.ui;
import com.itheima.service.IAccountService;
import com.itheima.service.impl.AccountServiceImpl;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
/**
 *
 */
public class Client {
    /**
     * 获取Spring的IOC核心容器,并根据id获取对象
     * @param args
     */
    public static void main(String[] args) {
        //1.获取核心容器对象
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象---两种方式
        IAccountService as = (IAccountService) ac.getBean("accountService");
        as.saveAccount();
        //没有调用销毁时,容器已经消失了
        //可以手动关闭容器
        ac.close();
    }
}
package com.itheima.service.impl;
import com.itheima.service.IAccountService;
/**
 * 账户的业务层实现类
 */
public class AccountServiceImpl implements IAccountService {
    //private IAccountDao accountDao = null;
    public AccountServiceImpl(){
        System.out.println("service对象创建了");
    }
    public void init(){
        System.out.println("对象初始化了");
    }
    public void destroy(){
        System.out.println("对象销毁了");
    }
    public void saveAccount() {
        System.out.println("service中的saveAccount方法执行了");
    }
}
四、依赖注入
1、概念
        依赖注入:Dependency Injection
        IOC的作用:
            降低/削减程序间的耦合程度(依赖关系)
        依赖关系的管理
            以后都交给了Spring维护
        在当前类中需要用到其他类的对象,由Spring为我们提供,我们只需要在配置文件中说明
        依赖关系的维护就称之为“依赖注入”
        依赖注入:
            能注入的数据由三类:
                基本类型和String
                其他bean类型(在配置文件中或者注解配置的bean)
                复杂类型/集合类型
            注入的方式有三种:
                第一种:使用构造函数提供
                第二种:使用set方法提供
                第三种:使用注解提供(明天的内容)
2、构造函数注入
<?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">
    <!--构造函数注入
        使用的标签:constructure-arg
        标签出现的位置:bean标签的内部
        标签中的属性:
            type:指定要注入数据的数据类型,该数据类型也是构造函数中某个或某些参数的类型
            index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值。参数索引的位置从0开始
            name:用于指定给构造函数中指定名称的参数赋值※常用的是名称
            ===================以上三个用于指定给构造函数中的哪个参数赋值=====================
            value:用于提供基本类型和String类型的数据
            ref:引用关联的bean对象,指定其他的bean类型数据,指的是在Spring的IOC容器中出现过的bean对象

        优势:在获取bean对象时,注入数据是必须操作,否则对象无法创建成功【不需要getset方法】
        弊端:改变了bean对象的实例化方式,使我们在创建对象时,如果用不到这些数据,也必须提供
    -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <constructor-arg name="name" value="字符串"></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="birthday" ref="now"></constructor-arg>
    </bean>
    <!--配置一个日期对象-->
    <bean id="now" class="java.util.Date"></bean>
</beans>
package com.itheima.service.impl;
import com.itheima.service.IAccountService;
import java.util.Date;
/**
 * 账户的业务层实现类
 */
public class AccountServiceImpl implements IAccountService {
    //如果是经常变化的数据,并不适用于注入的方式
    private String name;
    private Integer age;
    private Date birthday;//Bean类型
    public AccountServiceImpl(String name, Integer age, Date birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }
    public AccountServiceImpl() {
    }
    //private IAccountDao accountDao = null;
    public void saveAccount() {
        System.out.println("service中的saveAccount方法执行了..."+name+","+age+","+birthday);
    }
}
3、set方法注入
<?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="now" class="java.util.Date"></bean>
    <!--set方法注入※更常用
        涉及的标签:property
        出现的位置:bean标签的内部
        标签的属性:
            name:指定注入时所调用的set方法名称,关心set方法去掉set和大写
            ===================以上三个用于指定给构造函数中的哪个参数赋值=====================
            value:用于提供基本类型和String类型的数据
            ref:引用关联的bean对象,指定其他的bean类型数据,指的是在Spring的IOC容器中出现过的bean对象
        优势:
            创建对象时没有明确的限制,可以直接使用默认构造函数
        弊端:
            如果有某个成员必须有值,则获取对象时,有可能set方法没有执行
            即调用了AccountServiceImpl2构造,对象用完,set无法执行
    -->
    <bean id="accountService2" class="com.itheima.service.impl.AccountServiceImpl2">
        <property name="username" value="test"></property>
        <property name="age" value="21"></property>
        <property name="birthday" ref="now"></property>
     </bean>

</beans>
4、注入集合数据
<?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中的依赖注入
        依赖注入:Dependency Injection
        IOC的作用:
            降低/削减程序间的耦合程度(依赖关系)
        依赖关系的管理
            以后都交给了Spring维护
        在当前类中需要用到其他类的对象,由Spring为我们提供,我们只需要在配置文件中说明
        依赖关系的维护就称之为“依赖注入”
        依赖注入:
            能注入的数据由三类:
                基本类型和String
                其他bean类型(在配置文件中或者注解配置的bean)
                复杂类型/集合类型
            注入的方式有三种:
                第一种:使用构造函数提供
                第二种:使用set方法提供
                第三种:使用注解提供(明天的内容)
     -->
    <!--构造函数注入
        使用的标签:constructure-arg
        标签出现的位置:bean标签的内部
        标签中的属性:
            type:指定要注入数据的数据类型,该数据类型也是构造函数中某个或某些参数的类型
            index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值。参数索引的位置从0开始
            name:用于指定给构造函数中指定名称的参数赋值※常用的是名称
            ===================以上三个用于指定给构造函数中的哪个参数赋值=====================
            value:用于提供基本类型和String类型的数据
            ref:引用关联的bean对象,指定其他的bean类型数据,指的是在Spring的IOC容器中出现过的bean对象

        优势:在获取bean对象时,注入数据是必须操作,否则对象无法创建成功【不需要getset方法】
        弊端:改变了bean对象的实例化方式,使我们在创建对象时,如果用不到这些数据,也必须提供
    -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <constructor-arg name="name" value="字符串"></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="birthday" ref="now"></constructor-arg>
    </bean>
    <!--配置一个日期对象-->
    <bean id="now" class="java.util.Date"></bean>
    <!--set方法注入※更常用
        涉及的标签:property
        出现的位置:bean标签的内部
        标签的属性:
            name:指定注入时所调用的set方法名称,关心set方法去掉set和大写
            ===================以上三个用于指定给构造函数中的哪个参数赋值=====================
            value:用于提供基本类型和String类型的数据
            ref:引用关联的bean对象,指定其他的bean类型数据,指的是在Spring的IOC容器中出现过的bean对象
        优势:
            创建对象时没有明确的限制,可以直接使用默认构造函数
        弊端:
            如果有某个成员必须有值,则获取对象时,有可能set方法没有执行
            即调用了AccountServiceImpl2构造,对象用完,set无法执行
    -->
    <bean id="accountService2" class="com.itheima.service.impl.AccountServiceImpl2">
        <property name="username" value="test"></property>
        <property name="age" value="21"></property>
        <property name="birthday" ref="now"></property>
     </bean>

    <!--复杂类型(集合类型)的注入(两大类)
        用于给list结构集合注入的标签:list array set
        用于给map结构集合注入的标签:map prop
        结构相同,标签可以互换
    -->
    <bean id="accountService3" class="com.itheima.service.impl.AccountServiceImpl3">
        <property name="myStrs">
            <array>
                <value>aaa</value>
                <value>bbb</value>
                <value>ccc</value>
            </array>
        </property>
        <property name="myList">
            <list>
                <value>aaa</value>
                <value>bbb</value>
                <value>ccc</value>
            </list>
        </property>
        <property name="mySet">
            <list>
                <value>aaa</value>
                <value>bbb</value>
                <value>ccc</value>
            </list>
        </property>
        <property name="myMap">
            <map>
                <entry key="testA" value="aaa"></entry>
                <entry key="testB">
                    <value>BBB</value>
                </entry>
            </map>
        </property>
        <property name="myProp">
            <props>
                <prop key="testc">cccc</prop>
                <prop key="testd">ddd</prop>
            </props>
        </property>


    </bean>
</beans>
package com.itheima.service.impl;
import com.itheima.service.IAccountService;

import java.util.*;

/**
 * 账户的业务层实现类
 */
public class AccountServiceImpl3 implements IAccountService {
    //如果是经常变化的数据,并不适用于注入的方式
    private String[] myStrs;
    private List<String> myList;
    private Set<String> mySet;
    private Map<String,String> myMap;
    private Properties myProp;

    public void setMyStrs(String[] myStrs) {
        this.myStrs = myStrs;
    }

    public void setMyList(List<String> myList) {
        this.myList = myList;
    }

    public void setMySet(Set<String> mySet) {
        this.mySet = mySet;
    }

    public void setMyMap(Map<String, String> myMap) {
        this.myMap = myMap;
    }

    public void setMyProp(Properties myProp) {
        this.myProp = myProp;
    }

    public void saveAccount() {
        System.out.println(Arrays.toString(myStrs));
        System.out.println(myList);
        System.out.println(mySet);
        System.out.println(myMap);
        System.out.println(myProp);
    }
}
package com.itheima.ui;
import com.itheima.service.IAccountService;
import com.itheima.service.impl.AccountServiceImpl;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/**
 *
 */
public class Client {
    /**
     * 获取Spring的IOC核心容器,并根据id获取对象
     * @param args
     */
    public static void main(String[] args) {
        //1.获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象---两种方式
        /*IAccountService as = (IAccountService) ac.getBean("accountService");
        as.saveAccount();*/
        //没有调用销毁时,容器已经消失了
        //可以手动关闭容器
        IAccountService as = (IAccountService) ac.getBean("accountService3");
        as.saveAccount();
    }
}
五、今日课程总结IOC
  • 关注代码的健壮性
    • Spring的IOC能解决什么问题
    • 如何搭建Spring中基于xml的IOC环境
    • 如何通过依赖注入降低类之间的依赖关系
  • 明日:注解、注解IOC到底做了什么事




posted @ 2021-02-16 21:24  哥们要飞  阅读(163)  评论(0)    收藏  举报