spring应用 @Scope("prototype")
2020-03-24 本文已影响0人
程序员老帮菜
经常用到的是单例,scope="singleton",今天展示下prototype,直接撸代码
// 扫包
@ComponentScan({"com.xxx"})
public class AppConfig {
}
@Scope("prototype")
@Component
public class Prototype1Service {
}
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
//验证两次是不同对象
System.out.println(context.getBean("prototype1Service"));
System.out.println(context.getBean("prototype1Service"));
// 输出结果
// com.wucl.service.prototype.test1.Prototype1Service@182decdb
// com.wucl.service.prototype.test1.Prototype1Service@26f0a63f
}
}
直接获取两次对象,可以看到内存地址不同,这就是prototype与singleton区别
FAQ
- 问题1:如果Prototype1Service被一个单例对象注入还会是产生不同的对象吗
直接撸代码
@Component
// 默认单例
public class Prototype2Service {
@Autowired
private Prototype1Service prototype1Service;
public void abc(){
System.out.println("Prototype2Service");
System.out.println(prototype1Service);
}
}
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
//验证两次是不同对象
Prototype2Service prototype2Service1 = context.getBean(Prototype2Service.class);
prototype2Service1.abc();
Prototype2Service prototype2Service2 = context.getBean(Prototype2Service.class);
prototype2Service2.abc();
// 输出结果
// com.wucl.service.prototype.test1.Prototype1Service@71dac704
// com.wucl.service.prototype.test1.Prototype1Service@71dac704
}
}