spring源码之@lookup

"本文探讨了Spring中单例Bean与原型模式的转换,实例分析了`@Component`与`@Scope("prototype")`的使用,展示了如何在不同场景下获取独立副本。通过`@Lookup`注解,揭示了原型模式下每次请求的新实例特性。"
摘要由CSDN通过智能技术生成

我们都知道,spring 的Bean默认是单例的,当在不同的地方获取这个Bean的时候都是同一个。
但是如果我们指定了"prototype"原型模式呢。
结果是两个变量在不同的方法中使用的时候还是同一个

@Component
public class LA {

	@Autowired
	LB lb;

	public void printlnInfo(){

		System.out.println("lb-["+ lb +"]");
	}

	public void printlnInfo1(){

		System.out.println("lb-["+ lb +"]");
	}
}

@Component
@Scope("prototype")
public class LB {
}

	@Test
	public void LookupModel(){
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.scan("com.spring.lookup");
		context.refresh();
		LA la = context.getBean(LA.class);
		la.printlnInfo();
		la.printlnInfo1();

	}


//打印结果
lb-[com.spring.lookup.LB@184cf7cf]
lb-[com.spring.lookup.LB@184cf7cf]

@lookup注释,就是我们每次获取对象的时候,都从容器中取出一个新的对象。

@Component
public abstract class LC {

	public void printInfo(){
		LB lb = createLb();
		System.out.println("lb-["+ lb +"]");
	}

	public void printInfo1(){
		LB lb = createLb();
		System.out.println("lb-["+ lb +"]");
	}

	@Lookup
	public abstract LB createLb();
}

	@Test
	public void LookupModel(){
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.scan("com.spring.lookup");
		context.refresh();
		LC lc = context.getBean(LC.class);
		lc.printInfo();
		lc.printInfo1();

	}

//打印结果
lb-[com.spring.lookup.LB@3427b02d]
lb-[com.spring.lookup.LB@647e447]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木小同

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值