一、创建 bean 的四种方式
1. 调用类的默认构造方法
<bean id = "myBean" class = "com.study.spring.MyBean" />
2. 通过构造函数注入
<bean id = "myBean" class = "com.study.spring.MyBean" >
<constructor-arg value = "myParam" />
</bean>
3. 通过构造函数注入对象的引用
<bean id = "myBean" class = "com.study.spring.MyBean" />
<bean id = "myBean2" class = "com.study.spring.MyBean2" >
<constructor-arg ref = "myBean" />
</bean>
4. 通过工厂方法创建 bean
<bean id = "myBean" class = "com.study.spring.MyBean" factory-method = "myFactoryMethod" />
二、bean 的作用域 scope
<bean id = "myBean" class = "com.study.spring.MyBean" scope = "prototype" />
三、初始化和销毁 bean (init-method、destory-method)
<bean id = "myBean2" class = "com.study.spring.MyBean2"
init-method = "method_name" destory-method = "method-name" />
也可以为应用上下文中所有的 bean 定义默认的初始化和销毁方法
四、注入 bean 的属性
1. 属性注入(通过 setter 方法注入)
<bean id = "myBean2" class = "com.study.spring.MyBean2" >
<property name = "simpleType" value = "simpleValue" /> <!-- 简单属性注入,Spring 会自动判断和转化简单属性的类型 -->
<property name = "myBean" ref = "myBean" /> <!-- 引用其它 bean 属性的注入 -->
<property name = "orther">
<bean class = "com.study.spring.other" /> <!-- 内部 bean 的注入 -->
</property>
<constructor-arg>
<bean class = "com.study.spring.other" /> <!-- 也可以使用构造方法注入 -->
</constructor-arg>
</bean>
2. 装配集合 list、set、array 包括 <value /> <ref /> <null />
3. 装配 map 集合
4. 装配 properties 集合(java.util.Properties)
5. 装配 null 值
6. 使用 Spring 命名空间 P 简化书写:
<bean id = "user" class = "com.study.spring.User" >
p:userName = "goddess"
p:otherBean-ref = "otherBean" <!-- 类型引用比简单属性多了 "-ref" -->
</bean>
7. 使用 SpEL 表达式装配
<!-- 装配简单属性 -->
<property name = "inttype" value = "#{23}" />
<property name = "scientific" value = "#{1e4}" />
<property name = "floatType" value = "#{11.1}" />
<property name = "stringtype" value = "#{'goddess'}" />
<property name = "booleantype" value = "#{true}" />
<!-- 引用其它 bean -->
<!-- 操作类 -->