1、SpringIOC和DI

1、 Spring IOC(控制反转)
1.1 IOC的概念:

IOC的根本作用是解决程序间的耦合,将创建对象的权利交给容器或者工厂

  • 如下代码通过工厂模式创建对象
public class BeanFactory {
//创建对象
private static Properties props;
//定义一个Map,用于存放我们创建的对象,我们称这个map为容器
private static Map<String,Object> beans;
static {
try {
props = new Properties();
//通过类加载器产生输入流
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
    //获取properties文件流对象
    props.load(in);
    beans = new HashMap<String, Object>();
    //实例化容器
    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);
        System.out.println(beans.get("acountDao"));
    }
    }catch (Exception e){
        throw new ExceptionInInitializerError("初始化peoperties失败");
    }
}

/**
 * 根据bean名称获取对象
 * @param beanName
 * @return
 */
public static Object getBean(String beanName){
    return beans.get(beanName);
}
1.2Spring基于xml的环境搭建和入门
1.2.1创建一个普通的maven项目

项目结构

1.2.2导入spring-context坐标
<dependencies>    
<dependency>        
<groupId>org.springframework</groupId>        
<artifactId>spring-context</artifactId>        
<version>5.0.2.RELEASE</version>    
</dependency>
</dependencies>
1.2.3在resource下创建bean.xml文件,导入spring的基本约束
<?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="acountService" class="com.yunxiao.service.impl.AcountServiceImpl"></bean>
  <bean id="acountDao" class="com.yunxiao.dao.impl.AcountDaoImpl"></bean>
</beans>
1.2.4测试获取bean对象
public class Client {
  public static void main(String args[]){
      //1、获取spring核心容器对象
      ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
      //2、类型强转,获取bean对象
      IAcountService server = (IAcountService) ac.getBean("acountService");
      //3、获取bean对象
      IAcountDao dao = ac.getBean("acountDao",IAcountDao.class);
      System.out.println(server);
      System.out.println(dao);
  }
}
1.2.6ApplicationContext的三个实现类,ApplicationContext和BeanFactory的区别
package com.yunxiao.ui;
import com.yunxiao.dao.IAcountDao;
import com.yunxiao.service.IAcountService;
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;

/**
 * @author :
 * @date :Created in 2020/4/28 下午12:57
 * @description:${description}
 * @modified By:
 * @version: $version$
 */
public class Client {
    /**
     *
     * @param args
     * ApplicationContext的三个实现类:
     *      ClassPathXmlApplicationContext:可以加载类下面的配置文件,这个配置文件(bean.xml)必须在类路径下
     *      FileSystemXmlApplicationContext:可以加载任意路径下的配置文件(bean.xml)(必须有访问权限,且需要指定文件的绝对路径)
     *      AnnotationConfigApplicationContext:读取注解容器的
     * 核心容器的两个接口引发的问题:
     * ApplicationContext:单例对象使用
     *      在构建核心容器时,创建对象时立即加载的,就是在读取配置文件后立马就创建配置文件中配置的对象
     * BeanFactory:多例对象使用
     *      在构建核心容器时,创建对象的策略是延迟加载的方式。就是什么时候根据id获取对象了,才真正创建对象
     *
     *
     */
    public static void main(String args[]){
        //1、获取spring核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2、类型强转,获取bean对象
        IAcountService server = (IAcountService) ac.getBean("acountService");
        //3、获取bean对象
        IAcountDao dao = ac.getBean("acountDao",IAcountDao.class);
        System.out.println(server);
        System.out.println(dao);

        Resource resource = new ClassPathResource("bean.xml");
        BeanFactory factory = new XmlBeanFactory(resource);
        IAcountService service = (IAcountService)factory.getBean("acountService");
        System.out.println(service);
    }
}
1.2.7spring中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="acountService" class="com.yunxiao.service.impl.AcountServiceImpl"></bean>
  -->
  <!--第二种方式:
              使用普通工厂类中的方法创建对象(使用某个类中的方法创建对象,并存入spring容器)
  <bean id="instanceFactory" class="com.yunxiao.factory.InstanceFactory"></bean>
  <bean id="acountService" factory-bean="instanceFactory" factory-method="getAcountService"></bean>
  -->
  <!--第三种方式:
              使用工厂中的静态方法创建对象(使用某个类中的静态方法创建对象,并存入spring容器)
  <bean id="acountService" class="com.yunxiao.factory.StaticFactory" factory-method="getAcountService"></bean>
  -->
  <!--bean的作用范围
          bean的scope属性
          作用:指定bean的作用范围
          取值:
              singleton:单例(默认)
              prototype:多例
              request:作用web应用的请求范围
              session:作用于web应用的会话范围
              global-session:作用于集群环境的会话范围(全局会话范围)
  <bean id="acountService" class="com.yunxiao.service.impl.AcountServiceImpl" scope="singleton"></bean>
  -->
  <!--bean对象的生命周期
          单例对象
              出生:容器创建
              活着:容器在,对象就一只存在
              死亡:容器销毁,对象销毁
          多例对象
              出生:当我们是使用对象时spring框架为我们创建
              活着:对象只要在使用过程就一只存在
              死亡:当对象长时间不用,且没有其他对象引用时,由java的垃圾回收器回收
  -->
  <bean id="acountService" class="com.yunxiao.service.impl.AcountServiceImpl" scope="singleton"
        init-method="init" destroy-method="destroy"></bean>
</beans>
2、Spring DI(依赖注入)

DI(Dependency Injection)依赖注入:就是指对象是被动接受依赖类而不是自己主动去找,换句话说就是指对象不是从容器中查找它依赖的类,而是在容器实例化对象的时候主动将它依赖的类注入给它

2.1spring的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">

    <!--依赖注入:
            IOC的作用:江都程序间的耦合(依赖关系)
            依赖关系:都交给spring来维护
            在当前类需要用到其他类对象,由spring为我们提供,我们只需要在配置文件中说明
            依赖关系的维护:就称之为依赖注入
                能注入的数据:3类
                    基本类型和String类型
                    其他bean类型(在配置文件或者注解中配置过的bean)
                    复杂类型/集合类型
                注入的方式:
                    构造函数注入
                    使用set方法注入
                    使用注解提供-->

    <!--构造函数注入
        使用标签:constructor-arg
        标签位置在bean标签类
        标签中的属性:
            type:用于要指定注入的数据的数据类型,该类型也是构造函数中的某个或某些参数的类型
            index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值,索引的位置从0开始
            name:用于指定给构造函数给构造函数中指定名称赋值
            #####以上三个参数用于指定给哪个参数赋值#####
            value:用于提供基本类型和String类型数据
            ref:用于指定其他的bean类型数据,指的就是在spring核心容器中出现的bean对象
       优势:
            在获取bean对象时,注入数据是必须的操作,否则对象无法创建成功
       弊端:
            改变了bean对象的实例化的方式,使我们在创建对象时如果用不到这些数据,也必须要提供
           -->
    <bean id="acountService" class="com.yunxiao.service.impl.AcountServiceImpl">
        <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方法名称(setName)就是name
            value:用于提供基本类型和String类型数据
            ref:用于指定其他的bean类型数据,指的就是在spring核心容器中出现的bean对象
        优势:
            创建对象时没有明确的限制,可以直接使用默认的构造函数创建对象
        弊端:
            如果某个成员必须有值,则获取对象有可能set方法没有执行
        -->
    <bean id="acountService2" class="com.yunxiao.service.impl.AcountServiceImpl2">
        <property name="name" value="宙斯"></property>
        <property name="age" value="1111119"></property>
        <property name="birthday" ref="now"></property>
    </bean>

    
    <!--复杂类型注入/集合类型注入
        用于给list结构注入的标签有:list、array、set
        用于给map结构注入的标签有:map、props-->
    <bean id="acountService3" class="com.yunxiao.service.impl.AcountServiceImpl3">
        <property name="myString">
            <array>
                <value>AAAA</value>
                <value>BBBB</value>
                <value>CCCC</value>
            </array>
        </property>
        <property name="myList">
            <list>
                <value>足球</value>
                <value>男球</value>
                <value>兵乓球</value>
            </list>
        </property>
        <property name="mySet">
            <set>
                <value>ssssss</value>
                <value>wwwwww</value>
                <value>gggggg</value>
            </set>
        </property>
        <property name="myMap">
            <map>
                <entry key="testA" value="AAAAA"></entry>
                <entry key="testB" value="BBBBB"></entry>
            </map>
        </property>
        <property name="myProperties">
            <props>
                <prop key="doingA">AAAAA</prop>
                <prop key="doingB">BBBBBB</prop>
            </props>
        </property>
    </bean>
</beans>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值