@Scope(“prototype“) 注入单例 多例 代码讲解
1.注入bean @Scope(“prototype”) 开启多例这里注入了一个 name为studenttype为Student的bean@Servicepublic class StudentService {@Bean@Scope("prototype")public Student student(){System.out.println("Bean被加载到容器");return new
·
1.注入bean @Scope(“prototype”) 开启多例
这里注入了一个 name为student type为Student 的bean
@Service
public class StudentService {
@Bean
@Scope("prototype")
public Student student(){
System.out.println("Bean被加载到容器");
return new Student("张三",23);
}
}
启动类
@SpringBootApplication
public class Demo02Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Demo02Application.class);
System.out.println("ioc容器加载完成");
Student bean = (Student) context.getBean("student");
bean.setName("lisi");
System.out.println(bean.toString());
Student bean1 = (Student) context.getBean("student");
System.out.println(bean1.toString());
System.out.println(bean==bean1);
}
}
控制台输出
从输出可看出 :多例情况下,容器创建完成时不调用方法创建对象到容器中,在程序中获取时,才会将对象加载到容器中,而且每次调用生成的都是不同的对象
2.我们把注解 @Scope(“prototype”)去除
控制台输出结果
可得出:单例情况下,容器创建时调用方法创建对象到容器中,在程序中调用bean,直接从容器中拿取,且每次拿取的都是同一个对象。如果上一次对bean里的属性做了修改,那下一次拿取的就是修改过的bean
更多推荐
已为社区贡献1条内容
所有评论(0)