Spring中Bean的作用域singleton和prototype

什么是作用域

singleton:单例模式,IOC容器在初始化的时候就会创建bean对象,并且是唯一的一个对象,以后如果要从IOC容器中获取对象,都会获取到该对象,不会再新建对象。

prototype:多例模式,IOC容器在初始化的时候不会创建bean对象,而是在每次getBean()的时候创建对象,并且每getBean()一次就创建一个对象。

如何指定作用域:
1.在xml配置文件的bean标签中指定

<bean id="address" class="com.lee.entity.Address" scope="prototype">
</bean>

2.在注解中指定

@Controller
@Scope("prototype")
public class StudentController {

}

补充:singleton延迟加载(懒加载)可以让单例模式在创建IOC容器时不创建对象,延迟到getBean()的时候再创建对象。

实现方法,加@lazy注解

@Controller
@Scope("prototype")
@Lazy
public class StudentController {

}
发布了63 篇原创文章 · 获赞 28 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_41286145/article/details/102549522