Spring学习笔记2 - Bean定义和作用域

Bean是一个被实例化、组装,并通过Spring IoC容器所管理的对象。

 

Bean定义的属性

属性 描述
class 这个属性是强制性的,并且制定用来创建bean的bean类
name 这个属性指定唯一的bean标识符。在基于XML的配置元数据中,可以使用ID和/或name属性来制定bean标识符
scope 指定由特定的bean定义创建的对象的作用域
constructor-arg 用来注入依赖关系
properties 用来注入依赖关系
autowiring mode 用来注入依赖关系
lazy-initialization mode 延迟初始化的bean告诉IoC容器在它第一次请求时,而不是在启动时去创建一个bean实例
initialization方法  在bean的所有必须的属性被容器设置之后,调用回调方法。
destruction方法 当包含该bean的容器被销毁时,使用回调方法。 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Spring框架支持以下五个作用域 

・singleton:该作用域将bean的定义限制在每一个Spring IoC容器中的一个单一实例(默认) 

・prototype:该作用域将单一bean的定义限制在任意数量的对象实例

・request:该作用域将bean的定义限制为HTTP请求。(只在web-aware Spring ApplicationContext的上下文中有效。)

・session:该作用域将bean的定义限制为HTTP会话。(只在web-aware Spring ApplicationContext的上下文中有效。)

・global-session:该作用域将bean的定义限制为全局HTTP会话。(只在web-aware Spring ApplicationContext的上下文中有效。)

 

※singleton作用域:

如果作用域设置为singleton,那么Spring IoC容器刚好创建一个由该bean定义的对象的实例。

该单一实例将存储在这种单例bean的高速缓存中,以及针对该bean的所有后续的请求和引用都返回缓存对象。

示例:

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.xsd">

    <bean id="helloWorld" class="com.microyum.HelloWorld" scope="singleton">
        <property name="message" value="Hello World" />
    </bean>
</beans>

 

MainApp.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"beans.xml");
		HelloWorld hw1 = (HelloWorld) context.getBean("helloWorld");
		hw1.setMessage("I'm hw1");
		hw1.getMessage();

		HelloWorld hw2 = (HelloWorld) context.getBean("helloWorld");
		hw2.getMessage();

		System.out.println();
		hw2.setMessage("I'm hw2");
		hw2.getMessage();
		hw1.getMessage();

	}
}

  

输出结果:

Your Message : I'm hw1
Your Message : I'm hw1

Your Message : I'm hw2
Your Message : I'm hw2

 

※prototype作用域

如果作用域设置为prototype,那么每次特定的bean发出请求时,Spring IoC容器就创建对象的新的Bean实例。

示例:

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.xsd">

    <bean id="helloWorld" class="com.microyum.HelloWorld" scope="prototype">
        <property name="message" value="Hello World" />
    </bean>
</beans>

 

输出结果:

Your Message : I'm hw1
Your Message : Hello World

Your Message : I'm hw2
Your Message : I'm hw1

 

posted @ 2017-05-19 17:03  MicroYum  阅读(237)  评论(0编辑  收藏  举报