spring 源码解析之注解篇@Lookup

179 阅读1分钟

Lookup

在Spring框架中,@Lookup注解用于方法级别的依赖注入

当我们调用一个用@Lookup注解的方法时,Spring会返回该方法返回类型的一个实例。本质上,Spring会覆盖我们注解的方法,并使用我们的方法的返回类型和参数作为BeanFactory#getBean的参数。

@Lookup注解主要有以下两个用途:

  • 原型作用域(prototype-scoped)的bean注入到单例(singleton)bean中,使每次使用该 bean 都会创建一个新的 bean 实例。
  • 程序化地注入依赖。
 // 一个服务接口,其实现需要每次请求时都创建一个新的实例
 public interface MyService {
     void doSomething();
 }
 ​
 // MyService的一个具体实现,设置为原型作用域
 @Service
 @Scope("prototype")
 public class MyServiceImpl implements MyService {
     private final int id;
 ​
     public MyServiceImpl() {
         this.id = new Random().nextInt(100);
     }
 ​
     @Override
     public void doSomething() {
         System.out.println("Doing something with ID: " + id);
     }
 }
 ​
 ================================================================
   
 @Component
 public class SingletonComponent {
 ​
     // 使用@Lookup注解的方法会在运行时动态查找并注入由IoC容器管理的MyServiceImpl bean新实例
     @Lookup
     public MyService getNewServiceInstance() {
         // 这个方法体不会执行,Spring会替换这个逻辑来从容器中获取新的MyServiceImpl实例
         return null;
     }
 ​
     public void performActions() {
         // 每次调用getNewServiceInstance都会得到一个新的MyServiceImpl实例
         MyService service1 = getNewServiceInstance();
         service1.doSomething();
 ​
         MyService service2 = getNewServiceInstance();
         service2.doSomething();
 ​
         // 输出结果将会是两个不同的ID,表明它们是两个独立的实例
     }
 }
 ​