您的位置:首页 > 编程语言 > Java开发

7.Spring bean的声明周期

2017-12-18 18:19 274 查看

一.spring IOC容器可以管理Bean的生命周期

步骤:

1.通过构造器或工厂方法创建Bean

scope属性主要有两个singleton(单例)与prototype(多例模式),默认值为singleton。

<bean id="person" class="com" scope="prototype"/>
   Bean的创建时机主要由几个配置项共同来决定,包括:(具体介绍见Spring7.1)

scope属性,决定是Bean是单例模式(singleton)还是多例模式(prototype),默认为单例singleton;
lazy-init属性,只对单例模式有效,决定是否延时加载,默认为false,表示在容器初始化时,就会生成单例;
RequestMapping属性,这个注解MVC中才有,当有该属性时,lazy-init属性会失效(其实不是简单的冲突,而是RequestMapping会在另外的逻辑处理中生成单例);

2.为Bean的属性设置值和对其他的Bean的应用(依赖的对象)
3.调用Bean的初始化方法,init-method=""
4.Bean可以使用了
5.当容器关闭了,调用Bean的销毁方法,destroy-method=""

<bean id="person" class="com.Person" init-method="init" destroy-method="destroy">

二.Bean的执行流程

  首先上一张老图,这里主要是用BeanFactory来初始化容器时,创建Bean会经历的流程。如果使用ApplicationContext,则会有很多额外处理与功能。 



三.实例:

1.目录



2.代码

Person.java

package com;

a536

public class Person {
public Person() {
System.out.println("---------我是构造方法---------");
}

public void init() {
System.out.println("---------我是init初始化方法----");
}

public void destroy() {
System.out.println("---------我是destroy销毁方法--");
}
private Integer id;
private String name;

public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + "]";
}

}


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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="person" class="com.Person" init-method="init" destroy-method="destroy">
<property name="id" value="103"></property>
<property name="name" value="一天"></property>
</bean>

</beans>

Test.java
package test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.Person;

public class Test {

public static void main(String[] args) {
ConfigurableApplicationContext bf=new ClassPathXmlApplicationContext("beans.xml");
Person per=(Person) bf.getBean("person");

System.out.println(per);

//销毁bean
bf.close();
}
}

控制台打印结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: