Spring注解驱动 @Scope设置组件作用域

1. @Scope使用流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Configuration
public class BeanConfig {
@Scope("prototype") // 多实例
@Bean
public Person person() {
// 多实例,容器每获取一次Person,就会调用该方法
System.out.println("给容器添加Person");
return new Person("jack", 10);
}
@Scope("singleton") // 单实例
@Bean
public Car car() {
// 单实例,容器创建时,就会调用该方法
System.out.println("给容器添加Car");
return new Car();
}
}

测试方法

1
2
3
4
5
6
7
8
9
10
11
@Test
public void test() {
ApplicationContext ioc = new AnnotationConfigApplicationContext(BeanConfig.class);
// 每获取一次Person
Person person1 = (Person) ioc.getBean("person");
Person person2 = (Person) ioc.getBean("person");
Car car1 = (Car) ioc.getBean("car");
Car car2 = (Car) ioc.getBean("car");
System.out.println(person1 == person2);
System.out.println(car1 == car2);
}

panchaoxin wechat
关注我的公众号
支持一下