【Spring注解】3.@Scope作用域&4.@Lazy懒加载

微信公众号:程序yuan
关注可了解更多的资源。问题或建议,请公众号留言;

3.@Scope作用域

1.@Scope的源码

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {

    @AliasFor("scopeName")
    String value() default "";

    /**
     * prototype 多实例
     * singleton 单实例
     * request  同一个请求创建一个实例(一般不用)  
     * session  同一个session会话创建一个实例(一般不用)
     * 如果是web环境我们一般将对象存至request域&Session域
     */
    @AliasFor("value")
    String scopeName() default "";

    ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;

}

MainConfig.java

@Configuration
public class MainConfig2 {

    @Scope(scopeName = "prototype")
    @Bean
    public Person person(){
        return new Person("李四",25);
    }
}

测试:

@Test
    public void testScope(){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig2.class);
        String[] names = context.getBeanDefinitionNames();
        for(String name:names){
            System.out.println(name);
        }
        Person person1 = (Person) context.getBean("person");
        Person person2 = (Person) context.getBean("person");
        System.out.println(person1 == person2);
    }

2.singleton:

​ Bean组件在单实例(默认)的情况下,ioc容器在创建后就会调用方法把对象放到ioc容器中。以后每次获取就是直接从容器(类似map.get())中拿,而不会再次创建,所有person1 == person2 为true。

3.prototype:

​ Bean组件在多实例的情况下,ioc容器创建时不会直接调用方法将对象创建出来,而是在每一次获取对象的时候,ioc容器都会创建一个新的对象返回,即每次获取的对象都是不同的。所有person1 == person2 为false;

4.@Lazy懒加载

懒加载:

​ 单实例bean,默认是在容器启动的时候创建对象。

​ 使用懒加载时,将对象的创建推迟到第一次获取的时候。

1.@Lazy源码

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Lazy {

    /**
     * Whether lazy initialization should occur.
     */
    boolean value() default true;
}

2.不使用懒加载:

@Configuration
public class MainConfig2 {
    //@Lazy
    @Scope(scopeName = "singleton")
    @Bean
    public Person person(){
        System.out.println("创建person对象");
        return new Person("李四",25);
    }
}

测试文件:

@Test
public void testLazy(){
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig2.class);
    System.out.println("ioc容器创建完成");
}

 

3.使用懒加载:

MainConfig.java把@Lazy注解释放

测试文件:

@Test
public void testLazy(){
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig2.class);
    System.out.println("ioc容器创建完成");
    System.out.println("获取person对象");
    context.getBean("person");
}

 

总结:

​ 可以看出,不使用lazy懒加载时,容器创建时就创建了person对象。而使用了lazy时,就推迟到获取person

的时候创建的。

猜你喜欢

转载自blog.csdn.net/ooyhao/article/details/83591826