一、加载机制
注意最关键的:懒加载只能在单例模式下使用
单实例Bean:在容器启动时创建对象
懒加载:容器启动时,先不创建对象,获取到第一个Bean时创建对象
二、实现普通单例模式
2.1先创建一个domain类
package com.Bean; public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Bean{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
2.2创建一个Config类,定义Bean
package com.Config; import com.Bean.Person; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Scope; public class MainConfig { //默认是单列情况,通过添加@Scope注解,@Scope("prototype")变成多例 @Bean("person") public Person person() { System.out.println("添加person"); return new Person("李四",20); } }
2.3创建测试类
import com.Config.MainConfig; import com.Config.config; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class TestP { @Test public void test02(){ AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MainConfig.class); System.out.println("IOC容器创建完成"); }
2.4运行后
2.5我们可以发现在普通单实例创建下,容器在创建好的时候,Bean已经被添加进来了
三、实现懒加载
3.1在刚刚的Config类中的方法,添加上@Lazy注释
package com.Config; import com.Bean.Person; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Scope; public class MainConfig { //默认是单列情况,通过添加@Scope注解,@Scope("prototype")变成多例 @Bean("person") @Lazy public Person person() { System.out.println("添加person"); return new Person("李四",20); } }
3.2运行
我们会发现容器加载了但是Bean却没有添加进来
3.3在测试类中添加Bean
import com.Config.MainConfig; import com.Config.config; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class TestP { @Test public void test02(){ AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MainConfig.class); System.out.println("IOC容器创建完成"); Object person = annotationConfigApplicationContext.getBean("person"); }
}
3.4运行