@Scope(“prototype“) 注入单例 多例 代码讲解

本文通过示例展示了Spring中@Scope('prototype')注解如何实现Bean的多例,以及移除该注解后的单例行为。在多例模式下,每次从容器获取Bean时都会创建新的对象;而在单例模式下,容器初始化时会创建唯一对象,后续获取始终返回同一实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值