这里给出Bean的定义,还是英文的比较好理解,就不翻译了,怎么翻译怎么不对。
The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans.
Spring Ioc容器管理Bean的实例化、装配以及其他行为。Bean是容器由相对应的配置生成的,这样的配置可以是XML,正如前面看到的。
Bean的定义
Bean的定义需要的信息叫做configuration metadata (配置元数据),这些信息告诉容器以下几点:
- 如何创建Bean
- Bean的生命周期
- Bean的依赖
配置元数据
Configuration metadata 包含一系列属性:
No | name | Properties & Description |
---|---|---|
1 | class | 该属性是强制性的,用来指定用来创建Bean的Bean类 |
2 | name | 该属性指定了Bean的唯一标识符。在XML配置中,你可以使用id 或者 name 属性来指定bean的唯一标识符 |
3 | scope | 指定从一个特定的bean定义创建的对象的范围,在后续讨论 |
4 | constructor-arg | 通过构造函数注入的依赖,后续讨论 |
5 | autowiring mode | 用来注入依赖关系的,后续讨论 |
6 | lazy-initialization mode | 延迟初始化,如果设置true,表示当该bean第一次被请求的时候才会被创建,而不是在容器启动的时候 |
7 | initialization method | 回调-在bean的所有必须的属性被容器设置后会调用该函数 |
8 | destruction method | 当包含该bean的容器被销毁的时候调用该毁掉方法 |
Spring Configuration Metadata
IoC 容器与配置元数据实际写入的格式是完全分离的。以下三种方法提供给Spring 容器的配置元数据
- XML 文件配置
- 基于注解的配置
- Java config的配置
你已经看过基于XML的配置,让我们看看其他基于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">
<!-- A simple bean definition -->
<bean id = "..." class = "...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- A bean definition with lazy init set on -->
<bean id = "..." class = "..." lazy-init = "true">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- A bean definition with initialization method -->
<bean id = "..." class = "..." init-method = "...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- A bean definition with destruction method -->
<bean id = "..." class = "..." destroy-method = "...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
遇到的问题
在写到init-method和destroy-method时,发现怎么设置destroy-method,最后的销毁方法都没有被执行。
开始我的MainApp的方法是这样的:
package com.soygrow;
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 helloWorld = (HelloWorld) context.getBean("helloWorld");
helloWorld.getMessage();
helloWorld.setMessage("singleton test.");
HelloWorld helloWorld1 = (HelloWorld) context.getBean("helloWorld");
helloWorld1.getMessage();
}
}
这样写表示Application 没有结束,所以导致destroy-method怎么也不会执行,所以如果想执行你配置的destroy-method方法需要主动进行结束 context。我尝试的方法是:
((ClassPathXmlApplicationContext) context).close();
如果你将ApplicationContext替换成AbstractApplicationContext,那么context也是有close的方法的。
总之,需要将context 关闭才会调用destroy-method的方法。
Spring教程专栏地址:http://blog.csdn.net/column/details/19452.html