学过spring的都知道当在xml中配置bean时,会有一个scope的属性,它可以理解为是bean的作用域或者bean的范围。scope一般包括一下几种:
- singleton(默认)
- prototype
- request
- session
- global
- session
不懂得可以百度,这里不多做介绍了。我们这里要介绍的是,当采用注解方式来把bean加载到容器中时,怎么来设置这个scope。
当通过@Bean注解时,默认的就是单例的,如何验证呢?看下面代码
@Configuration // 相当于写了一个spring的xml配置文件
public class MyConfig {
@Bean("person")
public Person person(){
return new Person("JOHN");
}
}
public class AppliactionRunner {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
Object person = applicationContext.getBean("person");
Object person1 = applicationContext.getBean("person");
System.out.println(person1== person); // 结果为true
}
}
下面介绍如果通过@Scope来设置bean的作用域。
例子1:
@Configuration // 相当于写了一个spring的xml配置文件
public class MyConfig {
@Scope("prototype")//prototype与ConfigurableBeanFactory#SCOPE_PROTOTYPE中的值对应
@Bean("person")
public Person person(){
return new Person("JOHN");
}
}
public class AppliactionRunner {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
Object person = applicationContext.getBean("person");
Object person1 = applicationContext.getBean("person");
System.out.println(person1== person); // 结果为false
}
}
@Scope("singleton")和@Scope("prototype")的区别?
- @Scope("singleton")
那么在创建容器时,也就是在执行ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);时就会调用构造方法创建bean,而且只会创建这个一,以后只用这一个。当调用getBean方法时,就会去容器中拿这一个用
- @Scope("prototype")
创建容器时,也就是执行ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);时不会调用构造方法创造bean放到容器中,只有在执行applicationContext.getBean方法时才会去调用类的构造方法来创建bean,每次调用都会创建一个新的bean,而不是从容器中拿已经创建好的bean。所以才会使多实例的。