@Scope的作用 调整组件的作用域
package common.config;
import common.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class MainConfig2 {
/*
* @see ConfigurableBeanFactory#SCOPE_PROTOTYPE
* @see ConfigurableBeanFactory#SCOPE_SINGLETON
* @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST
* @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION
* prototype:多实例的
* singleton:单实例的
* request:同一次请求创建一个实例
* session:同一个session创建一个实例
*/
@Scope(value = "singleton")
@Bean
public Person person() {
System.out.println("创建person");
return new Person("lisi", 21);
}
}
package common;
import common.bean.Person;
import common.config.MainConfig2;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainTest {
@Test
public void test() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2.class);
System.out.println("IOC容器创建完成");
Person person = (Person) applicationContext.getBean("person");
Person person1 = (Person) applicationContext.getBean("person");
System.out.println(person == person1);
}
}
运行测试代码打印内容为:
可以看出当scope的value为singleton(默认值)时,IOC容器启动时会调用方法创建对象放到IOC容器中,以后每次获取都是从容器中直接获取。因此单实例情况下,不论什么时候获取实例,都是同一个。
再次改为多实例
package common.config;
import common.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class MainConfig2 {
/*
* @see ConfigurableBeanFactory#SCOPE_PROTOTYPE
* @see ConfigurableBeanFactory#SCOPE_SINGLETON
* @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST
* @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION
* prototype:多实例的
* singleton:单实例的
* request:同一次请求创建一个实例
* session:同一个session创建一个实例
*/
@Scope(value = "prototype")
@Bean
public Person person() {
System.out.println("创建person");
return new Person("lisi", 21);
}
}
执行上述测试代码,运行结果为:
当scope的value为prototype时,IOC容器启动时并不会调用方法创建对象放在容器中。而是每次获取的时候才会调用方法创建对象。