spring框架的学习-IOC容器(二)

来源:互联网 发布:mac f117笔记本 编辑:程序博客网 时间:2024/06/05 05:15

- IOC创建Bean的三种方式

  1. 默认构造方法创建Bean
  2. 静态工厂方法创建Bean
  3. 实例工厂方法创建Bean

代码实例

xml文件

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"><beans><!-- 通过构造方法创建Bean --><bean id="helloWorld" class="com.lzl.test.createbean.HelloWorld"></bean><!-- 通过静态工厂方法创建Bean --><bean id="helloWorldFactory" class="com.lzl.test.createbean.HelloWorldFactory" factory-method="getInstance"></bean><!-- 通过动态工厂方法创建Bean --><!-- 创建实例工厂Bean --><bean id="dynamicFactory" class="com.lzl.test.createbean.DynamicHelloWorldFactory"></bean><!-- 使用实例工厂创建Bean --><bean id="helloWorld1" class="com.lzl.test.createbean.HelloWorld" factory-bean="dynamicFactory"factory-method="getHelloWorld"></bean></beans>

代码实例

public static String path="";public static ApplicationContext fileResource;@Beforepublic void getFileResource(){    fileResource = new ClassPathXmlApplicationContext(path);}public class CreateBeanTest extends SpringHelper{    static{        path = "org/springframework/jmx/helloWorldCreateBean.xml";    }    @Test    public void createBean(){        HelloWorld h1 = (HelloWorld) this.fileResource.getBean("helloWorld");        HelloWorld h2 = (HelloWorld) this.fileResource.getBean("helloWorldFactory");        HelloWorld h3 = (HelloWorld) this.fileResource.getBean("helloWorld1");    }}

总结

SpringIOC

利用spring容器对对象的创建、初始化、和销毁(对象是単例才行)。

  1. 创建

    方式:

    1. 默认构造方法创建Bean
    2. 静态工厂方法创建Bean
    3. 实例工厂方法创建Bean

    时机:

    1. lazy-init为“default/false”,当启动spring的时候创建Bean。
    2. lazy-init为“true”时,使用getBean的时候创建bean
  2. 初始化
    1. spring容器调用init方法
    2. 在构造方法之后执行
  3. 销毁
    1. 如果是単例,则必须返回ClassPathXmlApplicationContext该容器,才能执行销毁工作。
    2. 如果是多例,容器不负责销毁。
0 0