说说Spring中为何要引入Lookup注解

 更新时间:2021年01月15日 14:37:30   作者:johnwonder  
这篇文章主要给大家介绍了关于Spring中为何要引入Lookup注解的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

我们先探一探官方文档关于Method Injection的章节是怎么说的:

In most application scenarios, most beans in the container are singletons. When a singleton bean needs to collaborate with another singleton bean or a non-singleton bean needs to collaborate with another non-singleton bean, you typically handle the dependency by defining one bean as a property of the other. A problem arises when the bean lifecycles are different. Suppose singleton bean A needs to use non-singleton (prototype) bean B, perhaps on each method invocation on A. The container creates the singleton bean A only once, and thus only gets one opportunity to set the properties. The container cannot provide bean A with a new instance of bean B every time one is needed.

用一句话概括就是 一个单例Bean A每次获取另外一个Bean B的时候怎么保证这个Bean B是一个新的实例?

正文

ApplicationContextAware接口

官方文档首先也提到了一个解决方案就是把A弄成容器的Aware( make bean A aware of the container),也就是实现ApplicationContextAware接口。

A solution is to forego some inversion of control. You can make bean A aware of the container by implementing the ApplicationContextAware interface, and by making a getBean("B") call to the container ask for (a typically new) bean B instance every time bean A needs it. The following example shows this approach

文档里随后就提供了一个示例来说明这个解决方案如何做。

// a class that uses a stateful Command-style class to perform some processing
package fiona.apple;
// Spring-API imports
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class CommandManager implements ApplicationContextAware {
 private ApplicationContext applicationContext;
 public Object process(Map commandState) {
  // grab a new instance of the appropriate Command
  Command command = createCommand();
  // set the state on the (hopefully brand new) Command instance
  command.setState(commandState);
  return command.execute();
 }
 protected Command createCommand() {
  // notice the Spring API dependency!
  return this.applicationContext.getBean("command", Command.class);
 }
  public void setApplicationContext(
   ApplicationContext applicationContext) throws BeansException {
  this.applicationContext = applicationContext;
 }
 }

虽然解决了一开始提出的问题,但是Spring随后就说到:

The preceding is not desirable, because the business code is aware of and coupled to the Spring Framework. Method Injection, a somewhat advanced feature of the Spring IoC container, lets you handle this use case cleanly.

也就是说 前面的方法是不可取的,因为业务代码知道并耦合到Spring框架。那怎么降低这个耦合度呢?后半句就给出了答案:方法注入是Spring IOC容器的一个稍微高级的特性,它允许您干净地处理这个用例。

Lookup Method方法注入

首先再次引入官方文档中的阐述:

Lookup method injection is the ability of the container to override methods on container-managed beans and return the lookup result for another named bean in the container. The lookup typically involves a prototype bean, as in the scenario described in the preceding section. The Spring Framework implements this method injection by using bytecode generation from the CGLIB library to dynamically generate a subclass that overrides the method.

简要概括下这段话有三个意思:

  • Lookup Method注入可以让容器重写容器中bean上的方法并返回容器中另一个bean的查找结果。
  • Lookup通常会是一个原型bean,如文章开头所说的。
  • Spring框架通过使用CGLIB库中的字节码生成来动态生成覆盖该方法的子类,从而实现这种方法注入。

使用Lookup方式需要注意以下几点:

  • For this dynamic subclassing to work, the class that the Spring bean container subclasses cannot be final, and the method to be overridden cannot be final, either.
  • Unit-testing a class that has an abstract method requires you to subclass the class yourself and to supply a stub implementation of the abstract method.
  • Concrete methods are also necessary for component scanning, which requires concrete classes to pick up.
  • A further key limitation is that lookup methods do not work with factory methods and in particular not with @Bean methods in configuration classes, since, in that case, the container is not in charge of creating the instance and therefore cannot create a runtime-generated subclass on the fly.

这段话也可以概括为以下几点:

  1. 使这个动态子类可以用,这个类不能是final,要重写的方法也不能是final。
  2. 单元测试具有抽象方法的类需要您自己对该类进行子类化,并提供抽象方法的存根实现。
  3. 具体的方法对于组件扫描也是必要的,这需要具体的类来获取。
  4. 一个关键限制是Lookup方法不适用于工厂方法,尤其是配置类中的@Bean方法,因为在这种情况下,容器不负责创建实例,因此不能动态创建运行时生成的子类。

接下来Spring就拿上面本来基于ApplicationContextAware的方法来说,就可以用Lookup来替换了。对于前面代码段中的CommandManager类,Spring容器动态重写createCommand()方法的实现。CommandManager类没有任何Spring依赖项,如修改后的示例所示

In the case of the CommandManager class in the previous code snippet, the Spring container dynamically overrides the implementation of the createCommand() method. The CommandManager class does not have any Spring dependencies, as the reworked example shows.

Xml配置lookup-method

 public abstract class CommandManager { 
  public Object process(Object commandState) {
   // grab a new instance of the appropriate Command interface
   Command command = createCommand();
   // set the state on the (hopefully brand new) Command instance
   command.setState(commandState);
   return command.execute();

 }
 // okay... but where is the implementation of this method?
  protected abstract Command createCommand();
 }

在包含要注入的方法的CommandManager类中,要注入的方法需要以下形式的签名:

<public|protected> [abstract] <return-type> theMethodName(no-arguments);

如果方法是抽象的,则动态生成的子类将实现该方法。否则,动态生成的子类将重写在原始类中定义的具体方法。

我们来看下Bean的配置:

当需要myCommand这个Bean的新实例时,被标识为commandManager的bean就会调用自己的createCommand()方法。如果需要的话,必须小心地将myCommand 这个bean部署为原型。如果是单例,则每次都返回相同的myCommand bean实例.

@Lookup注解

在基于注解的组件模型中,可以通过@lookup注释声明查找方法,如下例所示

 public abstract class CommandManager {
  public Object process(Object commandState) {
   Command command = createCommand();
   command.setState(commandState);
   return command.execute();
  }
  @Lookup("myCommand")
  protected abstract Command createCommand();
 }

或者,你也可以依靠目标bean根据lookup方法的声明返回类型进行解析

public abstract class CommandManager {
  public Object process(Object commandState) {
   MyCommand command = createCommand();
   command.setState(commandState);
   return command.execute();
  }
  @Lookup
  protected abstract MyCommand createCommand();
 }

需要注意的是你通常应该用一个具体的存根实现声明这种带注解的查找方法,以便它们与Spring的组件扫描规则兼容,默认情况下抽象类会被忽略。此限制不适用于显式注册或显式导入的bean类。也就是说如果用组件扫描Bean的话因为抽象类默认是被忽略的,但是你加上这个Lookup注解后就不会呗忽略。

Spring在最后也提供了其他两种解决思路:

Another way of accessing differently scoped target beans is an ObjectFactory/ Provider injection point. See Scoped Beans as Dependencies。You may also find the ServiceLocatorFactoryBean (in the org.springframework.beans.factory.config package) to be useful.

  1. 通过ObjectFactory或者ObjectProvider.
  2. 通过ServiceLocatorFactoryBean.

这两个方案我们之后会单独写文章来探讨,下篇文章我打算来具体的使用下这个Lookup 方法注入并且从源码角度来看下Spring如何巧妙地实现它的。

总结

到此这篇关于Spring中为何要引入Lookup注解的文章就介绍到这了,更多相关Spring为何引入Lookup内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 解读Hibernate、MyBatis有哪些区别

    解读Hibernate、MyBatis有哪些区别

    Hibernate和MyBatis是Java中常用的持久层框架,各有优势和适用场景,Hibernate通过对象关系映射简化数据库操作,适合复杂业务逻辑;MyBatis提供更高的SQL控制权,适合需要直接操作SQL的场景,选择应基于项目需求和团队习惯
    2025-01-01
  • Flink结合Kafka实现通用流式数据处理

    Flink结合Kafka实现通用流式数据处理

    这篇文章将和大家一起深入探讨Flink和Kafka的关系以及它们在数据流处理中的应用,并提供一些最佳实践和实际案例,希望对大家有一定的帮助
    2025-03-03
  • 浅谈String类型如何转换为time类型存进数据库

    浅谈String类型如何转换为time类型存进数据库

    这篇文章主要介绍了String类型如何转换为time类型存进数据库,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03
  • Java日期时间类(Date、DateFormat、Calendar)解析

    Java日期时间类(Date、DateFormat、Calendar)解析

    这篇文章主要介绍了Java日期时间类(Date、DateFormat、Calendar)解析,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-06-06
  • Spring Security自定义认证逻辑实例详解

    Spring Security自定义认证逻辑实例详解

    这篇文章主要给大家介绍了关于Spring Security自定义认证逻辑的相关资料,文中通过实例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2022-01-01
  • SpringBoot 下在 yml 中的 logging 日志配置方法

    SpringBoot 下在 yml 中的 logging 日志配置方法

    logging 配置主要用于控制应用程序的日志输出行为,可以通过配置定制日志的格式、级别、输出位置等,这篇文章主要介绍了SpringBoot 下在 yml 中的 logging 日志配置,需要的朋友可以参考下
    2024-06-06
  • Java多线程中sleep和wait区别

    Java多线程中sleep和wait区别

    本文主要介绍了Java多线程中sleep和wait区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-06-06
  • Java并发编程之CountDownLatch的使用

    Java并发编程之CountDownLatch的使用

    CountDownLatch是一个倒数的同步器,常用来让一个线程等待其他N个线程执行完成再继续向下执行,本文主要介绍了CountDownLatch的具体使用方法,感兴趣的可以了解一下
    2023-05-05
  • Java中的HashMap和Hashtable区别解析

    Java中的HashMap和Hashtable区别解析

    这篇文章主要介绍了Java中的HashMap和Hashtable区别解析,HashMap和Hashtable都实现了Map接口,但决定用哪一个之前先要弄清楚它们之间的区别,主要的区别有线程安全性、同步和速度,需要的朋友可以参考下
    2023-11-11
  • Springboot整合Mybatispuls的实例详解

    Springboot整合Mybatispuls的实例详解

    这篇文章主要介绍了Springboot整合Mybatispuls的相关资料,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-11-11

最新评论