@Scope 注解

作者: 宿命99 | 来源:发表于2018-04-17 14:48 被阅读46次

Spring 的 bean 默认都是单实例的, 如果我们想要每次都从 IoC 容器中获取的都是新的 bean 的实例,那么我们就需要使用多实例的 bean , 此时我们就要使用到 @Scope 注解

@Scope中的属性

value

scopeName

ScopeName 和 value 两个属性表示的是同一个意思, 他们互相定义了别名。 取值有两个
singleton (Spring IoC 容器默认就是单例的,可以不写)
prototype
这两个值在 ConfigurableBeanFactory 接口中有两个常量 SCOPE_SINGLETON 和 SCOPE_PROTOTYPE 在配置的时候,可以直接写字符串也可以使用这两个常量。

proxyMode

等价于 xml 配置 <aop:scoped-proxy/> 不经常使用


下面我们看代码验证
Person 类

public class Person {
    private String name;
    private Integer age;

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
// 省略 getter setter 和 toString 方法
}

配置类

@Configuration
public class ProtoTypeConfig {

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

测试代码

    @Test
    public void test4() {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(ProtoTypeConfig.class);
        Person person1 = ctx.getBean(Person.class);
        Person person2 = ctx.getBean(Person.class);
        System.out.println("person1 HashCode  " + person1.hashCode());
        System.out.println("person2 HashCode  " + person2.hashCode());
        System.out.println(person1 == person2);
    }

输出结果


取出的是两个不同的 bean

相关文章

网友评论

    本文标题:@Scope 注解

    本文链接:https://www.haomeiwen.com/subject/rapicftx.html