Spring注解 -- LookUp(单例Bean中使用多例Bean)

LookUp 的功能:

  1. 可以让我们在单例Bean中,使用多例Bean
  2. 可以在一个抽象类的某个方法上面标注@LookUp,从而让这个抽象类被注入到容器中

(实现ApplicationContextAware接口也能达到效果,不过有些场景不推荐,比如Controller....)

1. 关于在单例中使用多例,我举个例子:

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.extension.api.R;
@Component
@Scope("prototype")
public class Test1 {
	
	public R<String> test1(String string){
		return R.ok(string);
	}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

	@Autowired
	private Test1 test1;
	@Lookup
	public Test1 getTest1(){
		System.out.println("into....");
		return null;
	}
	
	@GetMapping("/lookProp")
	public String lookupProp(){
		System.out.println("@Autowired==>"+test1);
		System.out.println("@Autowired==>"+test1);
		System.out.println("--------------------------");
		System.out.println("lookup--->"+getTest1());
		System.out.println("lookup--->"+getTest1());
		return "success";
	}
}

输出结果:

@Autowired==>com.example.quartz.core.Test1@624351c9
@Autowired==>com.example.quartz.core.Test1@624351c9
--------------------------
lookup--->com.example.quartz.core.Test1@26476ae7
lookup--->com.example.quartz.core.Test1@2880905f

可以看出,直接使用@Autowired获取到的bean,没次使用都是同一个,Spring容器启动的时候,里面的属性都已经被赋值了

而使用LookUp标注的注解,每次获取到的都是不同的实例对象

而且可以看到,方法getTest1()中的输出并没有被执行,因为Spring在遇到LookUp标注的方法时,会重写此方法(在spring-beans:org.springframework.beans.factory.support.CglibSubclassingInstantiationStrategy,里面有个私有静态内部类LookupOverrideMethodInterceptor.intercept),因此返回值为null,对程序也没有影响。

2. 将抽象类放到容器中

如果不加@Lookup,则启动会报错

不过这个基本不会用到

import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component;
@Component
public abstract class AbstractTestService {
	
	@Lookup
	public Test1 test1(){
		return null;
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值