Bean的基本用法备忘

前言

本文为实验楼Spring框架入门教程 学习笔记

Spring中的相互引用

  • 引用不同配置文件中的Bean,可以使用ref标签,结合bean属性
  • 引用相同配置文件中的Bean,可以使用ref标签,结合local属性

ref 标签中 bean 属性,既可以引用相同xml文件中的bean,也可以引用不同xml文件中的bean,但是,考虑到项目的可读性,引用相同xml配置文件的bean时,应该尽量使用 local 属性。

Spring给bean属性注入value

示例给两个properties注入value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.shiyanlou.common;
public class FileNameGenerator {
private String name;
private String type;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

  • 一般方法:

    1
    2
    3
    4
    5
    6
    7
    8
    <bean id="FileNameGenerator" class="com.shiyanlou.common.FileNameGenerator">
    <property name="name">
    <value>shiyanlou</value>
    </property>
    <property name="type">
    <value>txt</value>
    </property>
    </bean>
  • 缩写方法:

    1
    2
    3
    4
    <bean id="FileNameGenerator" class="com.shiyanlou.common.FileNameGenerator">
    <property name="name" value="shiyanlou" />
    <property name="type" value="txt" />
    </bean>
  • “p” schema

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">


    <bean id="FileNameGenerator" class="com.shiyanlou.common.FileNameGenerator"
    p:name="shiyanlou" p:type="txt" />
    </beans>

注意
p语法需要添加xmlns:p="http://www.springframework.org/schema/p"

Bean的作用域

  • singleton — 单例模式,由IOC容器返回一个唯一的bean实例。
  • prototype — 原型模式,被请求时,每次返回一个新的bean实例。
  • request — 每个HTTP Request请求返回一个唯一的Bean实例。
  • session — 每个HTTP Session返回一个唯一的Bean实例。
  • globalSession — Http Session全局Bean实例。

一般情况下只需要使用单例模式和原型模式,并且默认情况下是单例模式。

Spring的集合类型Bean

  • List
  • Set
  • Map
  • Properties