SpringIOC及DI、Bean管理

一、SpeingIOC
1.SpringIOC控制反转

IOC容器:SpringIOC搭建Spring容器管理程序中的各个组件(class)让程序实现高内聚,低耦合的编程。

作用:解耦。管理javaEE项目,从而管理组件之间的耦合关系。

IOC(Inversion of Control,控制反转)是spring框架核心思想之一。

IOC是指将创建对象的控制权力交给spring框架去管理,Spring框架通过注解或者配置文件的方式,创建Bean对象并各个Bean之间的依赖关系,从而形成解耦

控制:是指将对象(实例化、管理)的权利

反转:控制权权利交给外部环境(Spring框架、Ioc、容器)

2.SpringIOC容器的理解

关键字: IOC容器的作用、存储形式、初始化过程

IOC通常理解为IOC Container容器,底层实质是Mapjihe,key为bean的id,value为bean对象。

功能:1.创建bean对象并管理bean生命周期;

         2.通过注解或者配置类管理各个bean之间的依赖关系,完成bean的注入。

IOC属于Spring Core模块,用来创建管理bean,默认方式为单例,存储在DefaultListBeanFactory类的BeanDefinitionMap中。

IOC容器使用ConcurrentHashMap集合存储了BeanDefinition对象,该对象封装了Spring对一个bean的所有配置信息。包括:类名,属性,构造方法参数,依赖,是否延迟加载,是否是单例等配置信息。

3.SpringIOC项目

   使用步骤:

    1.创建类
    2.将需要spring管理的类注入springIOC容器
        <bean id="唯一标识" class="类的完全限定名称"></bean>
    3.使用springIOC容器以解耦的方式创建JavaBean
        ApplicationContext  接口
        ClassPathXmlApplicationContext 实现类

    3.1高耦合

public class Test01 {
    public static void main(String[] args) throws  Exception {
/*方式一  链接数据库耦合度高*/
 DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/kj03?serverTimezone=GMT", "root", "root");
        System.out.println(connection);
}
}

       3.2耦合度中

public class Test01 {
    public static void main(String[] args) throws  Exception {
 /*方式二 链接数据库耦合度中*/
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/kj03?serverTimezone=GMT", "root", "root");
        System.out.println(connection);
}
}

jdbc.properties

msg1=com.mysql.cj.jdbc.Driver
msg2=jdbc:mysql://localhost:3306/kj03?serverTimezone=GMT
msg3=root
msg4=root

3.3低耦合 

public class Test01 {
    public static void main(String[] args) throws  Exception {
//3.通过key获取value
        String driver = properties.getProperty("msg1");
        String url = properties.getProperty("msg2");
        String name = properties.getProperty("msg3");
        String pwd = properties.getProperty("msg4");

        Class.forName(driver);
        Connection root = DriverManager.getConnection(url,name,pwd);
        System.out.println(root);
}
}

SpringIOC实现解耦:

SpringIOC如何实现解耦:
    1.不要直接new对象,反射构造
    2.把需要创建的对象信息不写死,而是保存在独立资源文件中动态加载


二、SpringDI

DI:(Dependecy Inject,依赖注入)是对IOC概念的不同角度的描述,是只应用程序在运行时,每一个bean对象都依赖IOC容器注入当前bean对象所需要的另一个bean对象。(例如在yBatis整合Spring时,SqlSessionFactoryBean依赖IOC容器注入一个DataSource数据源bean);

作用:将对象之间的依赖关系以注入方式实现耦合

1.SpringDI实现方式:

1.set注入(通过set方法实现依赖关系维护)

2.构造注入(通过构造方法实现依赖关系维护)

3.注解注入(通过注解实现依赖关系维护)

 2.SpringDI支持的数据类型

1.基本类型与String

2.javaBean

3.复杂类型(构造方式不支持)

3.SpringDI使用步骤:

1. 创建注入方式对应方法

2.配置标签

 4.SpringDI项目具体实现

4.1set注入+基本类型和String

   1.创建实体和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">
    <bean id="student" class="com.ly.pojo.Student">
        <!--========================set注入基本类型与String===============================-->
        <property name="stuName" value="依依"></property>
        <property name="stuAge" value="18"></property>
    </bean>
</beans>

4.2 Set注入+JavaBean

配置标签

<?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">
<!--========================set注入JavaBean===============================-->
    <bean id="userDao" class="com.ly.dao.UserDaoImpl"></bean>
    <bean id="imple" class="com.ly.service.UserServiceImple">
        <property name="dao" ref="userDao"></property>
    </bean>
    <bean id="userController" class="com.ly.controller.UserControllerImpl">
        <property name="service" ref="imple"></property>
    </bean>
</beans>

4.3Set注入+复杂类型

同样先创建实体类

package com.ly.pojo;


import java.lang.reflect.Array;
import java.util.*;

public class Teacher {
    private List mylist;
    private Set myset;
    private String[] myarray;
    private Map map;
    private Properties props;

    public void setMylist(List mylist) {
        this.mylist = mylist;
    }

    public void setMyset(Set myset) {
        this.myset = myset;
    }

    public void setMyarray(String[] myarray) {
        this.myarray = myarray;
    }

    public void setMap(Map map) {
        this.map = map;
    }

    public void setProps(Properties props) {
        this.props = props;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "mylist=" + mylist +
                ", myset=" + myset +
                ", myarray=" + Arrays.toString(myarray) +
                ", map=" + map +
                ", props=" + props +
                '}';
    }
}

第二步:配置文件

<?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">
    <!--========================set注入复杂类型===============================-->
    <bean id="teacher" class="com.ly.pojo.Teacher">
        <property name="mylist">
            <list>
            <value>剪刀面</value>
            <value>油泼面</value>
            <value>裤带面</value>    
            </list>
        </property>
        <property name="myset">
            <set>
                <value>原神</value>
                <value>蛋仔派对</value>
                <value>英雄联盟</value>
            </set>
        </property>
        <property name="myarray">
            <array>
                <value>iPhone</value>
                <value>HUAWEI</value>
                <value>小米</value>
                <value>vivo</value>
            </array>
        </property>
        <property name="map">
            <map>
                <entry key="你好" value="hello"></entry>
                <entry key="欢迎" value="welcome"></entry>
                <entry key="很好" value="nice"></entry>
            </map>
        </property>
        <property name="props">
            <props>
                <prop key="肖生克的救赎">摩根·弗里曼</prop>
                <prop key="孤注一掷">金晨</prop>
                <prop key="绿皮书">马赫沙拉·阿里</prop>
                <prop key="触不可及">小黑人</prop>
            </props>
        </property>
    </bean>
</beans>

4.4构造注入+基本类型和String

    1.创建实体类及对应方法

    2配置文件

    

<!--    ==============构造器方法基本类型和String=================-->
<bean id="student" class="com.ly.pojo.Student">
<!--    <constructor-arg name="stuName" value="蒋孝云"></constructor-arg>-->
<!--    <constructor-arg name="stuAge" value="18"></constructor-arg>-->

    <!--
    <constructor-arg index="0" value="18"></constructor-arg>
    <constructor-arg index="1" value="蒋孝云"></constructor-arg>-->

    <constructor-arg type="int" value="18"></constructor-arg>
    <constructor-arg type="java.lang.String" value="蒋孝云"></constructor-arg>
</bean>

4.5构造注入及JavaBean

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!--=========================bean的实例化(方式1)  默认无参构造=================================-->
    <!--<bean  id="student" class="com.ly.pojo.Student"></bean>-->
    <!--=========================bean的实例化(方式2)  默认无参构造=================================-->
<!--    <bean id="student" class="com.ly.pojo.Student" factory-bean="factory" factory-method="createStudent"></bean>-->
<!--          <bean id="factory" class="com.ly.factory.StudentFactory"></bean>-->
    <!--=========================bean的实例化(方式3)  默认无参构造=================================-->
<!--    <bean id="student" class="com.ly.factory.StaticStudentFactory" factory-method="createStu"></bean>-->
    <!--========================bean的作用域 单例===============================-->
<!--    <bean  id="teacher" class="com.ly.pojo.Teacher" scope="singleton"></bean>-->
    <!--========================bean的作用域 多例===============================-->
<!--    <bean  id="teacher" class="com.ly.pojo.Teacher" scope="prototype"></bean>-->
</beans>

三、SpringBean管理

  1.Bean的创建

     Bean的无参构造(默认)

     通过工厂创建对象

     通过静态工厂创建对象

2.Bean的作用域

     语法

<bean scope="作用域"></bean>

属性:

 Singleton   单例(默认)

prototype  多例

request   一个请求创建一个JavaBean

session   一个会话创建一个JavaBean

3.Bean的生命周期

实例化

属性赋值DI

初始化(接口初始化、属性初始化)

操作使用

销毁(接口销毁、属性销毁)

4.Bean具体项目:

实例和方法

package com.ly.pojo;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.naming.spi.InitialContextFactory;


@Component
@Scope
public class Teacher implements InitializingBean, DisposableBean {
    private String tname;
    public Teacher() {
        System.out.println("===>无参构造");
    }

    public void setTname(String tname) {
        this.tname = tname;
        System.out.println("======>属性赋值");
    }

    public void afterPropertiesSet() throws Exception {
        System.out.println("=====接口初始化====");
    }
    @PostConstruct
    public  void  doProp(){
        System.out.println("====属性初始化===");
    }

    public void destroy() throws Exception {
        System.out.println("接口销毁");
    }
    @PreDestroy
    public void doDestory(){
        System.out.println("======属性销毁======");
    }
}

 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    =========================bean的实例化(方式1)  默认无参构造=================================
    <bean  id="student" class="com.ly.pojo.Student"></bean>
    =========================bean的实例化(方式2)  默认无参构造=================================
    <bean id="student" class="com.ly.pojo.Student" factory-bean="factory" factory-method="createStudent"></bean>
          <bean id="factory" class="com.ly.factory.StudentFactory"></bean>
    =========================bean的实例化(方式3)  默认无参构造=================================
    <bean id="student" class="com.ly.factory.StaticStudentFactory" factory-method="createStu"></bean>
    ========================bean的作用域 单例===============================
    <bean  id="teacher" class="com.ly.pojo.Teacher" scope="singleton"></bean>
    ========================bean的作用域 多例===============================
    <bean  id="teacher" class="com.ly.pojo.Teacher" scope="prototype"></bean>
    ========================bean生命周期===============================
    <bean id="teacher" class="com.ly.pojo.Teacher" >
    <bean id="teacher" class="com.ly.pojo.Teacher" init-method="doProp" destroy-method="doDestory">
        <property name="tname" value="彭老师"></property>
     </bean>
</beans>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值