Spring的两大核心功能就是IOC和AOP,这篇文章主要介绍IOC。
简单来说,在面向对象思想下,A类中有一个B类的属性, 那么我们在创建A类时往往需要同时创建一个B类的对象,以便A类对其进行调用。但是,这样的后果便是,A类和B类的耦合度过高。所谓的IOC(控制反转),或者其实现的方式DI(依赖注入)。 实质就是Spring容器负责来创建A类、B类的实例,并在用户使用的时候将引用提供给用户。这样的好处就是用户不需要考虑创建实例,同时在一定程度上进行了解耦。

1.bean的配置

1.配置形式:

有三种配置形式,但是通常说两种:xml文件和注解,(有些书籍上说第三种是自动装配)。本文中主要介绍xml形式进行bean的配置。

2.配置方式:

bean的配置方式有三种:通过反射的方式进行配置;通过工厂方法(静态工厂、实例工厂);通过Spring提供的FactoryBean进行配置。

3.依赖注入的方式:属性注入、构造器注入

属性注入就是调用setter方法进行属性注入, 构造器注入方式是调用重载的带参构造器。
说到这里,可以来一些代码了:

<!--
        bean的配置方式1:通过全类名方式(反射)
        id:IOC容器中唯一存在,若不指定会默认使用全类名
    -->
    <bean id="car" class="com.spring.demo.bean.Car">
 <!--
        依赖注入方式1:属性注入,属性注入是通过setter方法注入bean的属性值或者依赖的对象。
        也是实际应用中最常用的方式。
        name指定属性值,value或者value节点指定属性值,ref指定依赖的对象
    -->
        <property name="company" value="大众"/>
        <property name="brand" value="宝来"/>
        <property name="price" value="200000.00"/>
        <property name="maxSpeed" value="200"/>
    </bean>

    <!--
       依赖注入方式2:构造器注入
       通过构造方法注入属性,能够保证bean在实例化后就能使用
       没有name属性,默认按照构造器的变量顺序加载,也可以通过index或者type进行限制
   -->
    <!--
       若一个 bean 有多个构造器, 如何通过构造器来为 bean 的属性赋值
       可以根据 index 和 value 进行更加精确的定位. (了解)
       也可以通过name来具体制定属性名进行绑定
       若字面值中包含特殊字符, 则可以使用 DCDATA 来进行赋值. (了解)
       使用构造器方式注入属性值时,可以使用type或index来区别重载构造器
   -->
    <bean id="car1" class="com.spring.demo.bean.Car">
        <constructor-arg value="宝马" type="java.lang.String"/>
        <constructor-arg value="mini" type="java.lang.String"/>
        <constructor-arg value="200000.00" type="double"/>
        <constructor-arg value="240" type="int"/>
    </bean>
    <!--
        依赖注入方式3:工厂方法注入
        因为这种方法比较少使用,这里只是写一下注释,没有demo
     -->

4.IOC容器BeanFactory和ApplicationContext简介

.BeanFactory是Spirng框架的基础设施,面向Spring本身;ApplicationContext是BeanFactory的子接口,面向Spring框架的应用者,其提供了更多的功能。
ApplicationContext具有两个只要的实现类:ClasspathXmlApplicationContext和FileSystemXmlApplicationContext;前者通过在类路径下加载配置文件来完成bean的装配,后者从文件系统下加载配置文件。项目结构如下所示:
Spring系列__02 IOC模块简介-LMLPHP
在这里,则可以进行测试了:

@Test
    public void teStetter() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean-ioc.xml");
        Car car = (Car) context.getBean("car");
        System.out.println(car);
    }

5.字面值

字面值可以用value标签或者value属性进行注入。基本类型及其包装类、String等都是采用字面值的方式进行注入。当具有特殊字符的时候,需要特殊处理:

<!--
        value简介:
            基本类型及其包装类、String都可以通过value标签或者value属性注入,
            当字面值包含特殊字符的时候,可用<![CDATA[]]>包含
     -->
    <bean id="car2" class="com.spring.demo.bean.Car">
        <property name="company" value="大众"/>
        <property name="brand">
            <value><![CDATA[<DZ宝来>]]></value>
        </property>
        <property name="maxSpeed" value="200"/>
        <property name="price" value="200000.00"/>
    </bean>

spring中某一属性不进行显式声明时,其会采用默认值,当然你可以显式的注入null:适应null标签
同时,spring支持级联属性的注入。

6.引用其他bean

当需要引用其他的bean时(A类引用B类),可以通过ref标签或者ref属性进行注入。其用法和value类似。泣别:value注入的是字面值,ref注入的是一个引用。当然,内部bean的注入也是这种方式。
示例如下:

<!--
        引入其他bean:
            例如person有car属性,需要引入,这是就不是使用value属性了,
            而是使用ref指定需要引入的bean
            也可以声明一个内部bean,此时内部bean就无需再指定id了,道理和内部类相似
    -->
    <bean id="person" class="com.spring.demo.bean.Person">
        <property name="name" value="丽丽"/>
        <property name="age" value="23"/>
        <property name="car" ref="car"/>
    </bean>

    <!-- innerBean -->
    <bean id="person1" class="com.spring.demo.bean.Person">
        <property name="name" value="丽丽"/>
        <property name="age" value="23"/>
        <property name="car">
            <bean class="com.spring.demo.bean.Car">
                <property name="brand" value="BMW"/>
                <property name="company" value="BMW"/>
                <property name="maxSpeed" value="233"/>
                <property name="price" value="233333.33"/>
            </bean>
        </property>
    </bean>

Spring系列__02 IOC模块简介-LMLPHP

7.集合属性

在Spring中可以通过xml标签配置集合属性:

1.list和数组

配置java.util.LIst和数组类型时,可以通过标签来配置,list中的属性可以使用value标签或者ref标签。
可以使用utility scheme来单独定义集合,这样的好处就是方便其他bean进行引用。

2.set

set的情况和list相似,使用set标签,用法和list标签一样。

<!--
        集合属性:
            list标签:数组和list数据使用这个标签,
            set标签:set数据使用,使用方法同list标签
    -->
    <bean id="stu" class="com.spring.demo.bean.Student">
        <property name="name" value="苏大强"/>
        <property name="age" value="60"/>
        <property name="cars">
            <list>
                <ref bean="car"/>
                <ref bean="car1"/>
                <ref bean="car2"/>
                <ref bean="car3"/>
            </list>
        </property>
    </bean>

    <!--
        也可以单独定义list,然后直接绑定
    -->
    <util:list id="carList">
        <ref bean="car"/>
        <ref bean="car1"/>
        <ref bean="car2"/>
        <ref bean="car3"/>
    </util:list>

    <bean id="stu1" class="com.spring.demo.bean.Student">
        <property name="name" value="苏大强"/>
        <property name="age" value="60"/>
        <property name="cars" ref="carList"/>
    </bean>

3.map和properties

java.util.Map可以通过map标签进行指定,map标签中有多个entity子标签,每个entity定义一对键值对。
在entity中可以通过key属性或者key标签来指定键,同理可以使用value、ref、bean、null属性或者标签指定值。

<!--
        map:
            map的使用可list相似,使用entry标签来保存每一对键值对,
            同时可以使用key属性或者key标签来存储key,
            value值或value属性绑定普通的字面值,ref绑定其他bean作为值
    -->
    <bean id="teacher" class="com.spring.demo.bean.Teacher">
        <property name="name" value="张莉"/>
        <property name="age" value="24"/>
        <property name="carMap">
            <map>
                <entry key="car" value-ref="car"/>
                <entry key="car1" value-ref="car1"/>
                <entry key="car2" value-ref="car2"/>
                <entry key="car3" value-ref="car3"/>
            </map>
        </property>
    </bean>

props标签用来定义java.util.Properties,该标签有子标签prop,具体使用方法与map一样。

8.p命名空间

Spring2.5之后支持p命名空间,可以简化xml配置,属性与原来的配置一样:

<!--
        spring2.5之后,可以使用p命名空间来简化属性配置,需要在配置文件中引入p命名空间
       xmlns:p="http://www.springframework.org/schema/p"
    -->
    <bean id="car4" class="com.spring.demo.bean.Car" p:brand="宝马" p:company="宝马"
          p:price="2000000.00" p:maxSpeed="200"/>

8.autowire

Spring的IOC容器可以通过自动装配来配置bean,使用方式就是使用autowire属性,有两种模式:byName和byType。byName会在Spring容器中根据名字取寻找匹配的bean,没有的话就无法完成装配;
byType会在Spring容器中按照类型来查找并进行bean的配置,但是当找到多个符合条件的类型的bean时会报异常。

<!-- 自动装配: 只声明 bean, 而把 bean 之间的关系交给 IOC 容器来完成 -->
    <!--
        byType: 根据类型进行自动装配. 但要求 IOC 容器中只有一个类型对应的 bean, 若有多个则无法完成自动装配.
        byName: 若属性名和某一个 bean 的 id 名一致, 即可完成自动装配. 若没有 id 一致的, 则无法完成自动装配
    -->
    <!-- 在使用 XML 配置时, 自动转配用的不多. 但在基于 注解 的配置时, 自动装配使用的较多.  -->
    <bean id="car" class="com.spring.demo.bean.Car">
        <property name="company" value="大众"/>
        <property name="brand" value="宝来"/>
        <property name="price" value="200000.00"/>
        <property name="maxSpeed" value="200"/>
    </bean>

    <bean id="person" class="com.spring.demo.bean.Person" autowire="byName">
        <property name="name" value="James"/>
        <property name="age" value="23"/>
        <property name="car" ref="carSub"/>
    </bean>

   <!-- <bean id="person1" class="com.spring.demo.bean.Person" autowire="byType">
        <property name="name" value="James"/>
        <property name="age" value="23"/>
    </bean>-->

    <!--
        自动装配的缺点:
            1.autowire默认会为bean装配全部属性,所以当你只想装配部分属性时显得不够灵活;
            2.byName和byType两种模式只能选择一个,不能兼有。

    -->

 @Test
    public void testByName() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean-autowire.xml");
        Person person = (Person) context.getBean("person");
        System.out.println(person);
    }

    @Test
    public void testByType() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean-autowire.xml");
        Person person = (Person) context.getBean("person1");
        System.out.println(person);
    }

9.bean的继承与依赖

作为一个Java程序员,肯定会接触到继承。Spring中也提供了bean的继承,思想和面向对象的继承的思想相似。区别在于Spring中的bean的继承是指bean的配置可以被继承(复用)。

<!--
        bean的继承:
            你可以定义一个bean并有其他bean继承,这样做的好处是能减少配置
            父bean的配置会由子bean继承,当然部分属性除外(autowire,abstract)
            子bean可以重新赋值一些属性,进行bean重新定义
            父bean可以定义为abstract,定义为abstract的bean只能被继承,不能被注册(实例化)
            父bean可以不定义class属性,由子类自己定义
            子bean需要通过parent属性指定你继承的父bean
    -->
    <bean id="carSup" class="com.spring.demo.bean.Car" p:company="宝马" p:brand="mini"
          p:maxSpeed="270" p:price="300000.00" abstract="true"/>

    <bean id="carSub" parent="carSup"/>

 @Test
    public void testInherit() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean-autowire.xml");
        Car car = (Car) context.getBean("carSub");
        System.out.println(car);
    }

在本文的开头,我们引入了A类和B类,当你想创建A类时,而A类又必须有B类的变量时,便可以使用依赖来解决这件事:

<!--
        bean的依赖:
            你可以声明当前bean依赖于哪些bean,这样当前bean初始化之前会去初始化依赖的bean,
            如果没有注册导致无法初始化便会报错
            依赖多个bean的时候,可以使用逗号或者空格分开
    -->
    <bean id="person1" parent="person" depends-on="carSub"/>

 @Test
    public void testDepends() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean-autowire.xml");
        Person person1 = (Person) context.getBean("person1");
        System.out.println(person1);
    }

9.bean的作用域

Spring中的bean的作用域有以下几种:
singleton, property, request,session
默认情况下,spring中每个bean只有一个实例,但是可以显示指定。

<!--
        bean的生命周期:
            singleton:默认选项,IOC容器默认为每个bean只实例化一个实例,该实例在调用具体的bean之前完成。
            property:原型。该方式下IOC容器会在每次调用bean的时候实例化一个新的实例,并且只有在调用时进行bean的初始化
           request和session同JavaWeb中一样,在此不多加介绍
    -->

    <bean id="dog" class="com.spring.demo.bean.Dog" p:name="haki" scope="prototype"/>

package com.spring.demo.bean;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@AllArgsConstructor
@ToString
public class Dog {
    private String name;
    public Dog() {
        super();
        System.out.println("dog's constructor");
    }
}

@Test
    public void testScope() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean-autowire.xml");
        Dog dog = (Dog) context.getBean("dog");
        Dog dog1 = (Dog) context.getBean("dog");
        System.out.println(dog == dog1);
    }

在上面的demo中,除了可以查看bean的创建个数,还应该查看bean的创建时机。

04-12 02:51