Spring框架自我总结(一)

来源:互联网 发布:应届生java程序员面试 编辑:程序博客网 时间:2024/06/15 09:42


Spring框架自我总结


目录

    • Spring简介
      • Spring基本知识
      • 控制反转IOC
      • 依赖注入DI
      • Spring容器
    • Spring配置
      • Bean配置
      • 使用外部属性文件
      • 整合多个配置文件


正文

Spring简介

Spring基本知识

  1. Spring理念是:使现有技术更加实用;本身是大杂烩整合现有的框架技术;加工对象工厂;

  2. Spring的优点:
    (1)轻量级框架;(轻量级:不带有侵略性API、对容器没有依赖性、易于配置、易于通用、启动时间较短)
    (2)Ioc容器—控制反转;
    (3)Aop—面向切面编程
    (4)对事务的支持;
    (5)对框架的支持;
           ……

  3. Spring 模块
    这里写图片描述

  4. 安装 SPRING TOOL SUITE:它是一个 Eclipse 插件,利用该插件可以更方便的在 Eclipse 平台上开发基于 Spring 的应用。

  5. 搭建 Spring 开发环境:
    (1)导入jar包:
           spring-core
           spring-beans
           spring-context
           spring-expression
           commons-logging
    (2)在 classpath 下或其它目录下建Spring的Bean配置文件:这些配置文件用于在 Spring IOC 容器里配置 Bean,可有一个或多个该文件,文件名自己取。

    控制反转IOC

  6. 控制反转: IOC(Inversion of Control):
    (1)控制的内容:控制是谁来控制对象的创建,传统的应用程序对象的创建是由程序本身创建的,使用Spring以后,对象是由Spring创建的;
    (2)反转:正转是指对象是由程序本身来创建的,反转是指程序不主动创建对象,而变为被动的接受对象。
    总结:以前对象是由程序本身创建的,使用Spring以后变为被动的接受对象。

    依赖注入DI

  7. DI(Dependency Injection) — IOC 的另一种表述方式:
    (1)依赖:两个方面:一是说bean对象创建依赖于容器;二是说bean对象的依赖资源(对象、 常量、字符串、二进制文件等等,即指给该对象成员变量赋的值);
    (2)注入:指bean对象依赖的资源由容器来设置和装配;
    (3)总结:Spring 干了两件事:
             创建对象;
             根据对象引用的关系,把它所依赖的资源进行装配(注入)

  8. Spring 支持 3 种依赖注入的方式:
    (1)构造器注入:用constructor-arg:

        按索引index匹配入参:

  <bean id="user1" class="com.ren.entity.User">    <constructor-arg index="0" value="李四"/>   </bean>

        按类型type匹配入参:

  <bean id="user3" class="com.ren.entity.User">    <constructor-arg  type="java.lang.String" value="丽丽"/>   </bean>

(2)构造器注入: setter注入:用property:
        要求:
         1)被注入的属性必须有setter方法;
        2)setter方法的名字必须为:set+属性名首字母大写(即自动生成的set、get方法);
        3)如果属性是boolean类型的,则没有get方法,使用is;

         常量注入:用value:
        字面值:可用字符串表示的值,可以通过 元素标签或 value 属性进行注入。
        基本数据类型及其封装类、String 等类型都可以采取字面值注入的方式
        若字面值中包含特殊字符,可以使用 <![CDATA[]]> 把字面值包裹起来。

 <bean id="user"  class="com.ren.entity.User" >    <property name="name" value="zs"></property>   </bean>

        bean注入:用ref:

<bean id="userServiceImpl"                      class="com.ren.dao.service.impl.UserServiceImpl">    <property name="UserDAO" ref="userDaoMysqlImpl"></property> </bean> 

        数组注入:用array:

<property name="books">    <array>        <value>java</value>        <value>Oracle</value>    </array></property>

        List注入:用list:

<property name="hobbies">    <list>        <value>打球</value>        <value>唱歌</value>    </list></property>

        set注入:用set

    <property name="games">        <set>            <value>lol</value>            <value>cf</value>            <value>dns</value>        </set>        </property>

        Map注入:用map

<property name="cards">    <map>        <entry key="中国银行1" value="12345"></entry>        <entry key="中国银行2" value="12345"></entry>        <entry>            <key><value>建设银行</value></key>            <value>12345677</value>        </entry>    </map></property>

        空注入:

<property name="car"><null/></property>

(3) p命名空间注入:先引入p命名空间

<bean id="student" class="com.ren.entity.Student" p:age="12" p:sex="女">

(4) c命名空间注入:先引入c命名空间

<bean id="student" class="com.ren.entity.Student" c:age="13" c:sex="男">

Spring容器

  1. 实例化Spring IOC 容器:BeanFactory或ApplicationContext
    (1)BeanFactory: IOC 容器的基本实现.
    (2)ApplicationContext: 提供了更多的高级特性. 是 BeanFactory 的子接口.
    (3)BeanFactory 是 Spring 框架的基础设施,面向 Spring 本身;
    (4)ApplicationContext 面向使用 Spring 框架的开发者,几乎所有的应用场合都直接使用 ApplicationContext 而非底层的 BeanFactory
    (5)无论使用何种方式, 配置文件时相同的.
  2. ApplicationContext:
    (1)ApplicationContext 的主要实现类:
    ClassPathXmlApplicationContext:从 类路径下加载配置文件
    FileSystemXmlApplicationContext: 从文件系统中加载配置文件
    (2)ApplicationContext 在初始化上下文时就实例化所有单例的 Bean。
    (3)WebApplicationContext 是专门为 WEB 应用而准备的,它允许从相对于 WEB 根目录的路径中完成初始化工作;
    这里写图片描述
  3. 从 IOC 容器中获取 Bean:

Spring配置

Bean配置

(1)基于 XML 文件的配置形式:

 <bean id="user" name="u1,u2 u3" class="com.ren.entity.User" scope="singleton">    <property name="name" value="zs"></property>  </bean>

            Bean标签:

     1).bean就是java的对象,由Spring来创建和管理;     2).id:是bean的标识符,要唯一;如果没有id时,name为默认的标识符;     3).如果配置了id,又配置了name,那么name就是别名,可以有多个;     4).class:是bean的全限定名,包名.类名;     5).如果不配置id和name,则在类中可以通过applicationContext.getBean(class)获取;     6).作用域:scope:       1> scope="singleton":单例,整个容器只有一个对象;(默认是单例)       2> scope="prototype":原型,每次获取bean都产生一个对象;       3> scope="request":每次请求时创建一个对象;       4> scope="session":在会话范围内创建一个对象;       5> scope="global session":只在prolet下用户,表示appliaction;       6> scope="appliaction":在应用范围内创建一个对象;

            property标签:
            property对应的是该对象的set方法所对应的那个名字,一般和成员变量一致;
        (2)xml配置中Bean的自动装配:
             自动装配 :autowire 简化Spring配置(可以在头中设置默认方式)
             1)no不使用自动装配;
            2)autowire=”byName”:根据名称(set 方法来的)去查找相应的bean,如果有则配上;
            3)autowire=”byType”:根据类型自动装配,不用管id,但是同一种类型的bean只能有一个;(建议使用byName)
            4)constructor:当通过构造器注入实例化bean时使用byType的方式装配构造方法;
        (3)基于注解的配置形式:
              1)例子:
这里写图片描述

TestObject.java:@Component

package com.ren.annoation;import org.springframework.stereotype.Component;@Componentpublic class TestObject {}

UserRespository.java

package com.ren.annoation.respository;public interface UserRespository {    public void save();}

UserRespositoryImpl.java

package com.ren.annoation.respository;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;import com.ren.annoation.TestObject;@Repository//如果有多个实现时,可以指明用哪个实现时用value属性(value="userRespositoryImpl")public class UserRespositoryImpl implements UserRespository{    //使用 @Autowired 自动装配 Bean    //某一属性允许不被设置:用required=false    @Autowired(required=false)    private TestObject testObject;    public void save()    {        System.out.println("执行userRespositoryImpl....");        System.out.println(testObject);    }}

UserRespositoryImpl2.java

package com.ren.annoation.respository;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;import com.ren.annoation.TestObject;@Repositorypublic class UserRespositoryImpl2 implements UserRespository{    @Autowired(required=false)    private TestObject testObject;    public void save()    {        System.out.println("执行userRespositoryImpl2....");        System.out.println(testObject);    }}

UserService.java

package com.ren.annoation.service;public interface UserService {    public void add();}

UserServiceImpl .java

package com.ren.annoation.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Service;import com.ren.annoation.respository.UserRespository;@Service(value="userService")public class UserServiceImpl implements UserService{    //@Autowired    //法二:解决有多个实现时指定某个特定的实现用@Qualifier指定,和@Autowired一起加在属性上    //@Qualifier("userRespositoryImpl2")    private UserRespository userRespository;    //法三:解决有多个实现时指定某个特定的实现用@Qualifier指定,和@Autowired一起加在set方法上    @Autowired    public void setUserRespository( @Qualifier("userRespositoryImpl2") UserRespository userRespository) {        this.userRespository = userRespository;    }    @Override    public void add() {        System.out.println("执行userServiceImpl。。");        userRespository.save();    }}

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"    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 http://www.springframework.org/schema/context/spring-context-4.1.xsd">    <!--         配置指定IOC容器扫描的包        resource-pattern:配置扫描的特定的子包(resource-pattern="respository/*.class)     -->    <context:component-scan base-package="com.ren.annoation">    </context:component-scan></beans>

     2)在 classpath 中扫描组件:
     组件扫描(component scanning): Spring 能够从 classpath 下自动扫描, 侦测和实例化具有特定注解的组件.
     特定组件包括:
     @Component: 基本注解, 标识了一个受 Spring 管理的组件
     @Respository: 标识持久层组件
     @Service: 标识服务层(业务层)组件
     @Controller: 标识表现层组件
     扫描到的组件的命名:
     默认为: 使用非限定类名, 第一个字母小写.
     也可以在注解中通过 value 属性值标识组件的名称
     使用:
     1》在组件类上使用特定的注解;
     2》在 Spring 的配置文件中声明 :
     base-package 属性指定一个需要扫描的基类包,Spring 容器将会扫描这个基类包里及其子包中的所有类;
     当需要扫描多个包时, 可以使用逗号分隔;
    如果仅希望扫描特定的类而非基包下的所有类,可使用 resource-pattern 属性过滤特定的类;
    <context:include-filter> 子节点表示要包含的目标类
    <context:exclude-filter> 子节点表示要排除在外的目标类
(4)使用 @Autowired 自动装配 Bean
@Autowired 注解自动装配具有兼容类型的单个 Bean属性
注意:
1)构造器, 普通字段(即使是非 public), 一切具有参数的方法都可以应用@Authwired 注解;
2)默认情况下, 所有使用 @Authwired 注解的属性都需要被设置. 当 Spring 找不到匹配的 Bean 装配属性时, 会抛出异常, 若某一属性允许不被设置, 可以设置 @Authwired 注解的 required 属性为 false;
3)默认情况下, 当 IOC 容器里存在多个类型兼容的 Bean 时, 通过类型的自动装配将无法工作. 此时可以在 @Qualifier 注解里提供 Bean 的名称. Spring 允许对方法的入参标注 @Qualifiter 已指定注入 Bean 的名称;
4) @Authwired 注解也可以应用在数组类型的属性上, 此时 Spring 将会把所有匹配的 Bean 进行自动装配;
5)@Authwired 注解也可以应用在集合属性上, 此时 Spring 读取该集合的类型信息, 然后自动装配所有与之兼容的 Bean;
6)@Authwired 注解用在 java.util.Map 上时, 若该 Map 的键值为 String, 那么 Spring 将自动装配与之 Map 值类型兼容的 Bean, 此时 Bean 的名称作为键值;

使用外部属性文件

(1)在src下建db.properties属性文件:

jdbc.user=rootjdbc.password=123456jdbc.driverClass=com.mysql.jdbc.Driverjdbc.jdbcUrl=jdbc:mysql://localhost:3306/数据库名jdbc.initPoolSize=5jdbc.maxPoolSize=10

        (2)在src下的Spring配置文件中引入外部属性文件db.properties:先加入context命名空间

    <context:property-placeholder location="classpath:db.properties"/>

        (3)在Spring配置文件中可使用 ${var}形式变量:

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="user" value="${jdbc.user}"></property>        <property name="password" value="${jdbc.password}"></property>        <property name="driverClass" value="${jdbc.driverClass}"></property>        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>        <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>    </bean> 

整合多个配置文件

<!--config.spring包下的 --><import resource="config/spring/beansUser.xml"/><!--类路径下的下的 --><import resource="classpath:beansUser.xml"/>


一起奔跑吧!
每天积累一点点,每天进步一点点!


0 1