Spring IOC学习

IoC基础

控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。没有IoC的程序中我们使用面向对象编程对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。

使用多种方式完美的实现了IoC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IoC。Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从Ioc容器中取出需要的对象。采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

ApplicationContext加载配置文件的方式:

当配置文件中的配置很多,不便于修改的时候,有如下几种解决方案:

写法1

//加载classpath

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext2.xml",”applicationContext2.xml);

写法2

//加载磁盘路径

ApplicationContext applicationContext = new FileSystemXmlApplicationContext("applicationContext2.xml",”applicationContext2.xml);

写法3:

在主配置文件中,引入其他的配置文件。

<import  resource="applicationContext2.xml"/>

BeanFactory与ApplicationContext区别?

ApplicationContext类继承了BeanFactory.

BeanFactory采用了延迟加载,在使用到这个类的时候,getBean()方法的时候才会加载这个类.

ApplicationContext类加载配置文件的时候,创建所有的类.

ApplicationContext对BeanFactory提供了扩展:

* 国际化处理、 事件传递、Bean自动装配、各种不同应用层的Context实现

***** 早期开发使用BeanFactory.

IOC装配Bean(XML)

* IOC:控制反转.将对象的创建权交给Spring.

* DI:依赖注入.DI需要有IOC环境的,DI在创建对象的时候,将对象的依赖的属性,一并注入到类中.

Spring框架Bean实例化的方式:

提供了三种方式实例化Bean.

* 无参数的构造方法实例化

* 静态工厂实例化:

* 实例工厂实例化:

无参数构造方法的实例化:

<!-- 默认情况下使用的就是无参数的构造方法. -->

<bean id="bean1"  class="cn.itcast.spring3.demo2.Bean1"></bean>

静态工厂实例化:

<!-- 第二种使用静态工厂实例化 -->

<bean id="bean2"  class="cn.itcast.spring3.demo2.Bean2Factory"  factory-method="getBean2"></bean>

实例工厂实例化:

<!-- 第三种使用实例工厂实例化 -->

<bean id="bean3"  factory-bean="bean3Factory"  factory-method="getBean3"></bean>

<bean id="bean3Factory"  class="cn.itcast.spring3.demo2.Bean3Factory"/>

Bean的其他配置:

id和name的区别:

id遵守XML约束的id的约束.id约束保证这个属性的值是唯一的,而且必须以字母开始,可以使用字母、数字、连字符、下划线、句话、冒号

name没有这些要求

***** 如果bean标签上没有配置id,那么name可以作为id.

***** 开发中Spring和Struts1整合的时候, /login.

<bean name=”/login” class=””>

现在的开发中都使用id属性即可.

类的作用范围scope:

scope属性 :

* singleton:单例的.(默认的值.)

* prototype:多例的.

* request:web开发中.创建了一个对象,将这个对象存入request范围,request.setAttribute();

* session :web开发中.创建了一个对象,将这个对象存入session范围,session.setAttribute();

* globalSession :一般用于Porlet应用环境.指的是分布式开发.不是porlet环境,globalSession等同于session;

实际开发中主要使用singleton、prototype

Bean的生命周期:

配置Bean的初始化和销毁的方法:

配置初始化和销毁的方法:

* init-method=”setup”

* destroy-method=”teardown”

执行销毁的时候,必须手动关闭工厂,而且只对scope=”singleton”有效.

Bean的生命周期的11个步骤:

1.instantiate bean对象实例化

2.populate properties 封装属性

3.如果Bean实现BeanNameAware 执行setBeanName

4.如果Bean实现BeanFactoryAware 或者ApplicationContextAware 设置工厂setBeanFactory 或者上下文对象setApplicationContext

5.如果存在类实现BeanPostProcessor(后处理Bean),执行postProcessBeforeInitialization

6.如果Bean实现InitializingBean 执行afterPropertiesSet

7.调用<beaninit-method="init"> 指定初始化方法 init

8.如果存在类实现BeanPostProcessor(处理Bean),执行postProcessAfterInitialization

9.执行业务处理

10.如果Bean实现 DisposableBean 执行destroy

11.调用<beandestroy-method="customerDestroy"> 指定销毁方法 customerDestroy

DI:Bean中属性注入的方式

Spring支持构造方法注入、setter方法注入和注解的方式:

1、构造器注入:

<bean  id="car"  class="cn.itcast.spring3.demo5.Car">

   //键值对注入

    <!--

    <constructor-arg  name="name" value="宝马"/>

    <constructor-arg  name="price" value="1000000"/>

     -->

   //下标索引加强注入

    <constructor-arg  index="0"  type="java.lang.String" value="奔驰"/>

    <constructor-arg  index="1"  type="java.lang.Double"value="2000000"/>

</bean>

一般情况下,使用构造器方式注入比较少用,更多地采用setter方法

2、setter方法注入:

* 普通属性:

* <property name=”属性名”value=”属性值”>

* 对象属性:

* <property name=”属性名” ref=”其他类的id或name”>

 

<bean  id="car2" class="cn.itcast.spring3.demo5.Car2">

    <!-- <property>标签中name就是属性名称,value是普通属性的值,ref:引用其他的对象 -->

    <property  name="name" value="保时捷"/>

    <property  name="price" value="5000000"/>

</bean>

setter方法注入对象属性:

<property  name="car2"  ref="car2"/>

 集合属性的注入:

<bean id="collectionBean"class="cn.itcast.spring3.demo6.CollectionBean">

    <!-- 注入List集合 -->

    <property name="list">

        <list>

            <value>童童</value>

            <value>小凤</value>

        </list>

    </property>

    <!-- 注入set集合 -->

    <property name="set">

        <set>

            <value>杜宏</value>

            <value>如花</value>

        </set>

    </property>

    <!-- 注入map集合 -->

    <property name="map">

        <map>

            <entry key="刚刚" value="111"/>

            <entry key="娇娇" value="333"/>

        </map>

    </property>

另一种写法:(很少用)

    <property name="map">

        <map>

    <entry>

      <key><value>复杂写法</value></key>

                     <value>花费时间多</value>

            </entry>

        </map>

    </property>

   <!-- 注入propertie属性文件 -->

    <property name="properties">

        <props>

            <propkey="username">root</prop>

            <propkey="password">123</prop>

        </props>

    </property>

</bean>

3、注解方法注入:

3.1、Spring的注解装配Bean

虽然完全使用注解在开发中并不是特别多,但是在框架整合的时候往往会用到注解的方式。

Spring2.5 引入使用注解去定义Bean

@Component  描述Spring框架中Bean

 

Spring的框架中提供了与@Component注解等效的三个注解:

@Repository 用于对DAO实现类进行标注

@Service 用于对Service实现类进行标注

@Controller 用于对Controller实现类进行标注

***** 三个注解为了后续版本进行增强的.

3.2、使用注解方式进行Bean的属性注入

* 普通属性:

@Value

*  对象属性:

@AutoWired

@Resource

 

普通属性;

@Value(value="itcast")

private String info;

 

对象属性:

@Autowired:自动装配默认使用类型注入.

@Autowired

    @Qualifier("userDao")        --- 按名称进行注入.

 

@Autowired

    @Qualifier("userDao")       

private UserDao userDao;

等价于

@Resource(name="userDao")

private UserDao userDao;

3.3、Bean其他的属性的配置:

配置Bean初始化方法和销毁方法:

* init-method 和destroy-method.

@PostConstruct 初始化

@PreDestroy  销毁

配置Bean的作用范围:

@Scope

名称空间p:注入属性

如果一个类的属性非常的多,从Spring2.5开始,Spring提供了名称空间P来帮我们注入属性。

p:<属性名>="xxx"引入常量值

p:<属性名>-ref="xxx"引用其它Bean对象

 一个标签注入多个属性

 

引入名称空间:

<beans xmlns="http://www.springframework.org/schema/beans"

   xmlns:p="http://www.springframework.org/schema/p"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xsi:schemaLocation="

http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

<bean  id="car2" class="cn.itcast.spring3.demo5.Car2" p:name="宝马"  p:price="400000"/>

<bean  id="person" class="cn.itcast.spring3.demo5.Person" p:name="童童"  p:car2-ref="car2"/>

SpEL:属性的注入

Spring3.0开始,还提供了一种新的注入方式:SpEL(Spring Expression Language)表达式注入。

语法:#{表达式}

<bean id=""value="#{表达式}"> 

 

<bean  id="car2" class="cn.itcast.spring3.demo5.Car2">

    <property name="name" value="#{'大众'}"></property>

    <property name="price" value="#{'120000'}"></property>

</bean>

 

 SpEL还能引用其他bean的属性和方法:

<bean id="person"  class="cn.itcast.spring3.demo5.Person">

    <!--<property name="name"  value="#{personInfo.name}"/>-->

<property name="name"  value="#{personInfo.showName()}"/>

    <property name="car2"  value="#{car2}"/>

</bean> 

<bean id="personInfo"class="cn.itcast.spring3.demo5.PersonInfo">

    <property name="name"  value="张三"/>

</bean>

Spring集成JUnit测试:

在测试类中直接使用注解加载配置文件、注入Service并进行测试,比之前简便许多。在开发中这种测试方式用的比较普遍。

1.程序中有Junit环境.

2.导入一个jar包.spring与junit整合jar包.

* spring-test-3.2.7.RELEASE.jar

3.测试代码:

package com.js.Test;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.js.demo1.UserService;
 
 
/**
 * 引入了jar包之后,就可以使用一些注解了
 * @RunWith(SpringJUnit4ClassRunner.class)写法固定
 * @author hdb
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class SpringTest {
    @Autowired
    private UserService userService;
    
    @Test
    public void demo1(){
        userService.sayHello();
    }
}

 

参考:https://blog.csdn.net/dove_knowledge/article/category/6818451/2

posted @ 2018-08-14 01:15  Coosee  阅读(178)  评论(0编辑  收藏  举报