Liuqichun's Blog

Spring|Bean的初始化、作用域

BeanDefinition 保存 Bean 的元信息,是 Bean 的“配料表”。

Bean 初始化的方式:

1、通过构造器初始化(不可变对象)

 1public class SimpleMovieLister {
 2
 3    // the SimpleMovieLister has a dependency on a MovieFinder
 4    private MovieFinder movieFinder;
 5
 6    // a constructor so that the Spring container can inject a MovieFinder
 7    public SimpleMovieLister(MovieFinder movieFinder) {
 8        this.movieFinder = movieFinder;
 9    }
10
11    // business logic that actually uses the injected MovieFinder is omitted...
12}

构造函数的索引从 0 开始

1<bean id="exampleBean" class="examples.ExampleBean">
2    <constructor-arg index="0" value="7500000"/>
3    <constructor-arg index="1" value="42"/>
4</bean>

2、通过 Setter 方法

 1public class SimpleMovieLister {
 2
 3    // the SimpleMovieLister has a dependency on the MovieFinder
 4    private MovieFinder movieFinder;
 5
 6    // a setter method so that the Spring container can inject a MovieFinder
 7    public void setMovieFinder(MovieFinder movieFinder) {
 8        this.movieFinder = movieFinder;
 9    }
10
11    // business logic that actually uses the injected MovieFinder is omitted...
12}

3、通过静态工厂实例化

定义使用静态工厂方法创建的 bean 时,请使用 class 属性来指定包含 static 工厂方法的类,并使用名为 factory-method 的属性来指定工厂方法本身的名称。

容器执行 bean 依赖项解析,如下所示:

循环依赖

循环依赖:A -> B; B -> C; C ->A;

使用构造器注入会因为循环依赖抛异常。

自动装配模式

Bean 作用域

Scope Description
singleton (默认)将每个 Spring IoC 容器的单个 bean 定义范围限定为单个对象。
prototype 将单个 bean 的定义范围限定为任意数量的对象实例
request 将单个 bean 的定义范围限定为单个 HTTP 请求的生命周期。也就是说,每个 HTTP 请求都会根据单个 bean 定义创建一个实例。仅在可以感知网络的 Spring ApplicationContext 中有效。
session 将单个 bean 定义的范围限定为 HTTP Session 的生命周期。仅在可感知网络的 Spring ApplicationContext 上下文中有效。
application 将单个 bean 定义的范围限定为 ServletContext 的生命周期。仅在可感知网络的 Spring ApplicationContext上下文中有效。
websocket 将单个 bean 定义的范围限定为 WebSocket 的生命周期。仅在可感知网络的 Spring ApplicationContext 上下文中有效。

<< Previous Post

|

Next Post >>

#Spring