美文网首页
spring应用 @Scope("prototype")

spring应用 @Scope("prototype")

作者: 程序员老帮菜 | 来源:发表于2020-03-24 16:13 被阅读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

    }
}

直接获取两次对象,可以看到内存地址相同,这就是prototype被单例对象引用后,会丢失prototype的特点

相关文章

网友评论

      本文标题:spring应用 @Scope("prototype")

      本文链接:https://www.haomeiwen.com/subject/smooyhtx.html