欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-12 23:07:58
前言我们先探一探官方文档关于method injection的章节是怎么说的:in most application scenarios, most beans in the container ar...

前言

我们先探一探官方文档关于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内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!