package com.spring.config;
import com.spring.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Configuration
//@Lazy注解作用于类上时,通常与@Component及其衍生Spring注解配合使用。
/*@Component
@Lazy*/
public class TestLazyConfig {
// @Lazy注解属性 Value 取值为 true、false 。默认为true 表示启用懒加载。
//false 表示不启用,基本用不到,如果不启用的话,不需要加@Lazy注解
// @Lazy注解作用于在类方法上时,通常与@Bean注解配合使用。
@Lazy
@Bean
public Person person() {
System.out.println("测试容器添加Person对象......");
return new Person("小孙", 28, "西安");
}
}
package com.spring.test;
import com.spring.config.TestLazyConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestLazy {
public static void main(String[] args) {
// @Lazy 注解启用的时候 不进行类初始化,
// 不启用的时候会进行类初始化
//控制台输出:测试容器添加Person对象......
AnnotationConfigApplicationContext annotationContext = new AnnotationConfigApplicationContext(TestLazyConfig.class);
// 第一次获取Bean对象 会进行类初始化
//控制台输出:测试容器添加Person对象......
Object person1 = annotationContext.getBean("person");
// 第二次获取Bean对应 不会载进行类初始化
Object person2 = annotationContext.getBean("person");
}
}
IT技术分享社区
个人博客网站:https://programmerblog.xyz
联系客服