LookUp 的功能:
- 可以让我们在单例Bean中,使用多例Bean
- 可以在一个抽象类的某个方法上面标注@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;
}
}