1.说明
单例:内存中只有一份
多例:内存中有多份
- 默认情况下,spring管理的都是单例模式
package com.jt.config;
import com.jt.demo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
@ComponentScan("com.jt")
public class SpringConfig {
@Bean
// @Scope("singleton") //默认值 单例模式
@Scope("prototype") //多例模式
public User user(){
return new User();
}
}
2.懒加载
- 如果spring容器创建,对象立即创建则该方式称为“立即启动” – 容器启动创建
- 如果spring容器创建,对象在被使用时才创建,被称为“懒加载” --用时创建
@Lazy 表示懒加载
测试
package com.jt.config;
import com.jt.demo.User;
import org.springframework.context.annotation.*;
@Configuration
@ComponentScan("com.jt")
public class SpringConfig {
@Bean
// @Scope("singleton") //默认值 单例模式
//@Scope("prototype") //多例模式
@Lazy
public User user(){
return new User();
}
}
打个断点,查看什么时候创建加载
多例和懒加载的关系
- 只要是多例模式都是懒加载,只有在单例模式下才能控制懒加载有效
什么时候才能用到懒加载
1.服务器启动时,如果加载太多资源必然导致服务器启动慢,适当的将不重要的资源设置为懒加载。
2.有时用户会需要一些特殊的“链接”,而这些链接的创建需要时间很长,可以使用懒加载。