=================================== Spring IoC注解配置之Lazy和Scope注解 =================================== 1 默认饿汉单例 @Component(value = "student") public class Student { ... public Student() { System.out.println("Student类的构造器"); } ... } public class SpringTest { public static void main(String[] args) { ... System.out.println("获取sa对象"); Student sa = context.getBean("student", Student.class); System.out.println(Integer.toHexString(System.identityHashCode(sa))); System.out.println("获取sa对象"); Student sb = context.getBean("student", Student.class); System.out.println(Integer.toHexString(System.identityHashCode(sb))); ... } } 例程:AnnotationIoC Student类的构造器 \ 获取sa对象 | 34123d65 | 饿汉单例 获取sa对象 | 34123d65 / 2 添加Lazy注解 @Component(value = "student") @Lazy(value = true) public class Student { ... } 例程:AnnotationIoC 获取sa对象 \ Student类的构造器 | 1bb5a082 | 懒汉单例 获取sa对象 | 1bb5a082 / Lazy注解用于声明此类单例的饿汉/懒汉模式,相当于bean标签的lazy属性: - false(默认):饿汉模式 - true:懒汉模式 3 添加Scope注解 @Component(value = "student") @Scope(value = "prototype") public class Student { ... } 例程:AnnotationIoC 获取sa对象 \ Student类的构造器 | 5e0e82ae | 多例模式 获取sa对象 | Student类的构造器 | 6771beb3 / Scope注解用于声明此类的对象模式,相当于bean标签的scope属性: - singleton(默认):单例 - prototype:多例