我爱编程

李刚《Java EE企业应用实战》(第四版)第七章——Sprin

2016-06-28  本文已影响0人  Slience无言

Spring的定义和相关知识点

Spring包括

Spring的优点

Spring的搭建和一个小例子

下载和使用

本篇以Spring4.3为例,在Java EE - Eclipse中使用
先选择要下载的版本,之后进去选择那个最大的文件下载,在这里就是spring-framework-4.3.0.RELEASE-dist.zip
下载地址
之后在解压出来的文件夹在spring-framework-4.3.0.RELEASE\libs中的所有jar文件拷贝到项目文件中的WebContent/WEB_INF/lib文件夹中(之后可以在Java Resources/Web App Library中设置一下doc和源代码的设置,我这里就不写了)之后在Web App Libraries中可以看到如下的内容

粘贴到lib文件夹中会自动显示在Web App Libraries
这样我们就做好了一个Spring的环境了,之后还要有commons-logging的jar包,在网上搜索commons-logging-1.2.jar下载下来之后粘贴到lib文件夹里就好,接下来我们做一个小示例说明一下

小示例

首先我们写一个Animat动物接口,里面有say和move方法来表示动物都有的发声和移动行为,如下:

package com.impl;
public interface Animal {
    /**
     * 动物发出声音的方法
     * @return
     */
    public String say();
    
    /**
     * 动物移动的方法
     * @return
     */
    public String move(); 
}

之后写两个这个接口的实现类Cat和Dog
Cat.java

package com.entity;

import com.impl.Animal;

public class Cat implements Animal {

    @Override
    public String say() {
        // TODO Auto-generated method stub
        return "喵喵喵";
    }

    @Override
    public String move() {
        // TODO Auto-generated method stub
        return "小猫咪脚步静悄悄的";
    }

}

Dog.java

package com.entity;

import com.impl.Animal;

public class Dog implements Animal {

    @Override
    public String say() {
        // TODO Auto-generated method stub
        return "汪汪汪";
    }

    @Override
    public String move() {
        // TODO Auto-generated method stub
        return "小狗跑得很欢快";
    }
    
}

写好这两个动物的实现类之后我们再写一个Person类,来代表人,每个人都有一个动物这个动物可以是猫也可以是狗
Person.java

package com.entity;

import com.impl.Animal;

public class Person {
    private String name;
    private Animal animal;
    public Animal getAnimal() {
        return animal;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setAnimal(Animal animal) {
        this.animal = animal;
    }
}

在以前如果我们要指定这个人有一只狗会这样写

Person person = new Person();
Cat cat = new Cat();
person.setAnimal(cat);
person.setName("王小明");

这样做会在代码里面写死,日后要修改的就比较麻烦了,如果使用Spring的话就不一样了,使用Spring的时候要在src文件夹下新建一个xml文件,这个文件的名字一般叫做beans.xml,我们再这个文件里面配置各种JavaBean,在这个例子中我们的beans.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"
    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    <!-- 创建一个叫做cat的bean,它所对应的class是com.entity.Cat -->
    <bean id="cat" class="com.entity.Cat"/>
    <!-- 同上 -->
    <bean id="dog" class="com.entity.Dog"/>
    <!-- 创建一个叫做person的bean,它所对应的class是com.entity.Person -->
    <bean id="person" class="com.entity.Person">
        <!-- 设置person这个bean中的animal参数的值是cat这个JavaBean -->
        <property name="animal" ref="cat"/>
        <!-- 设置person这个bena中name参数是'王小明' -->
        <property name="name" value="王小明"/>
    </bean>
</beans>

这样我们就把一只猫和一个人相关联起来了,还把人的名字设置成了"王小明",现在我们来测试一下,测试代码可以这样写

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
Person person = applicationContext.getBean("person", Person.class);
System.out.println("我叫" + person.getName());
System.out.println("我的宠物叫:" + person.getAnimal().say());
System.out.println("我的宠物移动:" + person.getAnimal().move());

我们通过ApplicationContext 来找到是哪个bean的,ClassPathXmlApplicationContext方法中的参数就是在src文件夹下配置bean的那个xml文件的名字,获取了ApplicationContext 之后可以通过bean的id找到这个bean了。这样做的好处就是我如果要把狗狗赋给人的话只需要在xml配置文件中把<property name="animal" ref="cat"/>改成<property name="animal" ref="dog"/>就可以了,而且我这里没有配置bean所以默认都是单例模式,这样在请求多个同样class的bean获取到的bean都是同一个bean,系统不需要再去new一个bean了节约了系统的开销。

关于依赖注入

在上个例子中person类并没有对animal成员变量进行设置,但是还是可以获取得到person的animal的值并可以调用animal的say方法,这是由于使用了Spring来配置bean才能实现这样的效果的,使用这种方法需要在Person类中有setAnimal()方法。
之后我们在beans.xml中配置了这个bean的相关参数之后就会自动调用setAnimal方法,这是一种比较好的解耦方式。依赖注入让Spring的Bean以配置文件组织在一起,而不是以硬编码的方式耦合在一起。
由此可见,Spring的核心功能有两个

获取对象的方式

关于依赖注入和控制反转——其实两者是一样的

控制反转是指调用者获取被依赖对象的方式由原来的主动获取编程了被动接受,而依赖注入是指Spring容器负责将依赖对象赋值给调用者的成员变量——相当于为调用者注入它依赖的实例。所以可见依赖注入和控制反转是同一件事情只不过控制反转是以调用者的角度去描述,而依赖注入是以Spring容易的角度去描述的。
在这里李刚老师做了一个很生动的例子

设值注入

    <!-- 创建一个叫做person的bean,它所对应的class是com.entity.Person -->
    <bean id="person" class="com.entity.Person">
        <!-- 设置person这个bean中的animal参数的值是cat这个JavaBean -->
        <property name="animal" ref="cat"/>
        <!-- 设置person这个bena中name参数是'王小明' -->
        <property name="name" value="王小明"/>
    </bean>

构造注入

    <bean id="person" class="com.entity.Person">
        <constructor-arg name="name" value="张三"/>
        <constructor-arg ref="dog" name="animal"/>
    </bean>

使用这个构造注入的时候要在Person类中有一个接收String和Animal参数的构造函数。

两种构造方式的对比

Spring的相关使用

事件机制

Spring的世界框架有两个重要成员

让bean获取Spring容器

一般都是用Spring容器来创建bean,那bean有没有办法获取创建它的bean呢?具体的方法就是在bean中实现ApplicationContextAware接口,之后实现setApplicationContext,那么在创建这个bean的时候就可以在这个方法中获取到创建它的bean

    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        // TODO Auto-generated method stub
        System.out.println("获取到创建bean的ApplicationContext了:" + arg0.getDisplayName());
    }

bean的别名

在配置bean的时候需要指定id和class,分别代表着这个bean的唯一标识和所对应的具体实现类。我们还可以指定name属性(或者使用alias标签),这个属性就是bean的别名,例如

<bean id="cat" class="com.entity.Cat" name="spirit"/>

那么cat的别名就设置成了spirit了,这时我们对person创建与cat的依赖的时候就可以这样设置

    <bean id="person" class="com.entity.Person">
        <constructor-arg name="name" value="张三"/>
        <constructor-arg ref="spirit" name="animal"/>
    </bean>

如果一个bean要同时指定多个别名的话可以使用英文逗号、冒号或者空格分隔

bean的作用域

可以在bean标签中对scope属性进行设置,常用的作用域有5种

使用prototype创建的bean在创建完成之后Spring就不再跟踪实例,也不会维护bean的状态。
如果不指定bean的状态,那么默认是singleton,这种作用域在创建之后可以重复利用,可以减少系统的开销。应该尽量使用singleton。

注入集合

举个例子
MyList.java这个bean

package com.entity;

import java.util.List;
import java.util.Map;

public class MyList {
    private List<String> lists;
    private Map<String, String> maps;
    public List<String> getLists() {
        return lists;
    }
    public void setLists(List<String> lists) {
        this.lists = lists;
    }
    public Map<String, String> getMaps() {
        return maps;
    }
    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }
    
}

之后在beans.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"
    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    <!-- 使用p的XML Schema简化配置 -->
    <!-- p:lists是指MyList这个类中的lists的值是my.lists的值 -->
    <bean id="myList" class="com.entity.MyList"
        p:lists-ref="my.lists"
        p:maps-ref="my.maps"
    />
    <util:list id="my.lists" list-class="java.util.ArrayList">
        <value>星期一</value>
        <value>星期二</value>
        <value>星期三</value>
    </util:list>
    <util:map id="my.maps" map-class="java.util.HashMap">
        <entry key="晴天" value="去郊游"/>
        <entry key="雨天" value="去看书"/>
        <entry key="阴天" value="收拾房间"/>
    </util:map>
</beans>

测试方法

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        MyList myList = applicationContext.getBean("myList", MyList.class);
        System.out.println("lists=" + myList.getLists());
        System.out.println("maps=" + myList.getMaps());

这样就可以为list和map赋值了,与之类似的是util:set来配置Set

Spring的表达式语言SpEL

(我还没怎么接触,先不写这个)

上一篇下一篇

猜你喜欢

热点阅读