单实例bean:默认在容器启动时就会被创建
懒加载:容器启动不创建对象,在第一次使用(获取)时创建对象,并初始化
@Configuration public class MainConfig2 { @Lazy @Bean("person") public Person person() { System.out.println("person 被创建"); return new Person(15, "zhangsan"); } }
@Test public void test02() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig2.class); System.out.println("IOC容器创建完成"); Person bean1 = (Person) context.getBean("person"); Person bean2 = (Person) context.getBean("person"); System.out.println(bean1 == bean2); }
IOC容器创建完成 person 被创建 true