当前位置 博文首页 > blackball1998的博客:多实例Bean
在Spring中,Bean默认是单例的,也就是说当我们向IOC容器中添加一个Bean,多次获取Bean,默认是同一个Bean,我们也可以显示地声明Bean为单例,使用@Scope
设置属性为singleton即可
@Configuration
public class MyConfiguration {
@Bean
@Scope("singleton")
public Person person(){
return new Person(18,"wang");
}
}
现在我们多次获取Bean,测试两次获取的Bean是否为同一个对象
@SpringBootTest
class DemoApplicationTests {
@Autowired
Person person1;
@Autowired
Person person2;
@Test
void contextLoads() {
System.out.println(person1 == person2);
}
}
测试结果如下
说明是同一个Bean
将@Scope
的值改为prototype,则该Bean为多例属性,每次从容器中取出,都是取出一个该Bean的原型复制出来的对象
@Configuration
public class MyConfiguration {
@Bean
@Scope("prototype")
public Person person(){
return new Person(18,"wang");
}
}
测试用例如下
@SpringBootTest
class DemoApplicationTests {
@Autowired
Person person1;
@Autowired
Person person2;
@Test
void contextLoads() {
System.out.println(person1 == person2);
}
}
测试结果如下
以上测试说明确实从IOC容器中取出不同的两个Bean
需要注意的是,多例模式对系统开销比较大,一般情况下使用默认的单例模式即可
如果Bean使用@Component
添加,则将@Scope
添加在类名上
@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
@Scope("prototype")
public class Person {
private int age = 18;
private String name = "wang";
}