延迟初始化Bean
只有在真正使用的时候才创建以及初始化的Bean
在<bean>标签上指定属性lazy-init的属性值为true 即可延迟初始化Bean
Spring容器会在创建容器时提前初始化”singleton”的bean即单例的bean.Spring容器预先初始化Bean可以提前发现配置中的错误,所以尽量不开启延迟初始化Bean,除非有某个Bean需要大量的资源并且在整个程序的生命周期中基本用不到则可以设置.
延迟初始化的Bean的初始化:
- 第一次使用
- 作为延迟初始化的bean被非延迟的bean作为依赖对象注入时会随着该bean初始化被初始化
depends-on
<bean id="beanA" dependes-on="beanB">,beanA指定属性depends-on为beanB,所以beanB会在beanA初始化之前初始化,会在beanA销毁之后销毁
好处:
- 确保初始化beanA之前,beanB的资源已经准备好了
- 避免销毁beanB之后,beanA还在保持着资源的访问,造成资源不能释放或者释放错误
自动装配
推荐使用@Autowired注解
使用注解必须在配置文件上使用<context:annotation-config/>进行注解的扫描
依赖检查
推荐使用@Required注解
使用注解必须在配置文件上使用`进行注解的扫描
必须使用在setter方法上
如
Student .java
public class Student {
private Integer age;
private String name;
@Required
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
@Required
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
applicationContext.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<!-- student bean -->
<bean id="student" class="com.yiibai.Student">
<property name="name" value="FSL" />
<!-- 把age注释 -->
<!-- property name="age" value="24"-->
</bean>
</beans>
会抛出异常并打印Property 'age' is required for bean 'student'

被折叠的 条评论
为什么被折叠?



