bean作用域
scope:singleton | prototype
执行时机(产生bean的时机):
- singleton:容器在初始化时,就会创建对象(唯一的一个对象),以后getBean()时,不再产生新的bean对象。
singleton也支持延迟加载(懒加载):在第一次使用时产生对象。@Lazy- prototype:容器在初始化时,不创建对象,只是在每次使用(每次从容器中获取bean对象,getBean()),再创建对象,并且每次使用都创建一个新的对象
注解方式
@Scope用于指定bean作用域,默认是singleton
@Lazy表示延迟加载,在第一次使用时(getBean()时)产生bean对象
示例:
@Configuration
//@ComponentScan(value ={"org.lyh.controller","org.lyh.service"})
public class MyConfig {
@Bean//bean的id就是方法名
@Scope
@Lazy
public Student myStudent(){
Student student = new Student(2,"李健康",21);
student.setAddress(new Address("兰考县","商丘市睢阳区"));
return student;
}
}
xml方式
scope用于指定bean作用域,默认是singleton
lazy-init="true"表示延迟加载,在第一次使用时(getBean()时)产生bean对象
示例:
<bean id="student" class="org.lyh.entity.Student" scope="singleton" lazy-init="true">
<!--<property name="stuNo" value="1"></property>-->
<property name="stuNo" value="1"> </property>
<property name="stuName" value="刘玉慧"> </property>
<property name="stuAge" value="21"> </property>
<property name="address" ref="address"> </property>
</bean>