Bean的懒加载及依赖
<bean class="com.kdy.beans.User" id="user" depends-on="wife" ></bean>
<bean class="com.kdy.beans.Wife" id="wife" lazy-init="true"></bean>
1、使用depends-on = "xxx" 能够改变加载顺序 多个可以用,隔开
2、使用 lazy-init="true" 在使用实例时 才触发初始化
3、在 beans 中加入lazy-init="true" 所有的都会变成懒加载
Bean的作用域
<bean class="com.kdy.beans.Person" id="person" scope="singleton"></bean>
scope="singleton" 默认值 单例 同一个ID 无论使用多少次 都只实例化1次
<bean class="com.kdy.beans.Person" id="person" scope="prototype"></bean>
scope="prototype" 多例 每使用一次创建一个新的实例
单例会涉及线程安全问题,共享对象 会造成数据覆盖 脏数据问题。
下面了解即可 request 一个http每一次请求 创建一个bean
session 一个客户端对应一个bean
application 将bean限定为ServletContext的生命周期
websocket 将单个bean第一范围限定为webSocker的生命周期
实例化Bean
默认使用无参构造函数
使用了cons…… 使用默认构造函数
使用静态方法实例化Bean
1、类中添加静态方法
public static Person createPersonFactory(){
Child child = new Child();
child.setName("孩子");
return child;
}
2、Bean中指定实例化方法
<bean class="com.kdy.beans.Person" id="person" factory-method="createPersonFactory"></bean>
第二种实现方式
1、创建工厂类
package com.kdy.beans;
public class PersonFactory {
public Person createPersonMethod(){
Child child = new Child();
child.setName("2儿子");
return child;
}
}
2、注册Bean
<bean class="com.kdy.beans.Person" id="person2" factory-bean="personFactory" factory-method="createPersonMethod"></bean>
<bean class="com.kdy.beans.PersonFactory" id="personFactory"></bean>
自动注入
<bean class="com.kdy.beans.Person" id="person" autowire="byType"></bean>
<bean class="com.kdy.beans.Wife">
<property name="realname" value="张喵喵"></property>
</bean>
autowire="byType" 根据类型自动注入
当存在多个类型一样的 可以使用 autowire="byName"
<bean class="com.kdy.beans.Wife" name="wife">
<property name="realname" value="张喵喵"></property>
</bean>
<bean class="com.kdy.beans.Wife" name="wife2">
<property name="realname" value="王喵喵"></property>
</bean>
还可以使用 autowire="constructor" 使用构造函数等方式进行自动注入
多个类型 可以设置 primary="true" 来设置自动注入的优先级 或 使用 autowire-candidate="false" 关闭自动注入
Bean的生命周期的回调
1、实现接口InitializingBean 及 DisposableBean ,并重写相应的方法。
2、基于配置的指定方法 init-method destroy-method
<bean class="com.kdy.beans.Person" id="person" autowire="constructor" init-method="initMethod" destroy-method="desMethod"></bean>
先调用接口的生命周期回调 后调用配置的生命周期回调
3、注解方式 @PostConstruct @PreDestory
使用Bean管理第三方bean对象及加载配置文件
<bean class="com.alibaba.druid.pool.DruidDataSource">
<property name="username" value="${mysql.username}"></property>
<property name="password" value="${mysql.password}"></property>
<property name="url" value="${mysql.url}"></property>
<property name="driverClassName" value="${mysql.driverClassName}"></property>
</bean>
<context:property-placeholder location="db.properties"></context:property-placeholder>
Spring的表达式语言(SpEL) Spring Expression Language
基于XML 基于注解 基于代码
<bean class="com.kdy.beans.Person" id="person">
<property name="id" value="#{1+3}"></property>
<property name="wife" value="#{wife}"></property>
<property name="name" value="#{wife.realname}"></property>
<!-- 直接调用静态方法 -->
<property name="birthday" value="#{T(com.kdy.beans.PersonFactory).getNowDate()}"></property>
</bean>