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

Spring Annotaion Support详细介绍及简单实例

程序员文章站 2023-08-13 22:23:52
     最近正在看spring官网,看spring ioc的时候看spring容器扩展点的时候发现了beanpostprocess...

     最近正在看spring官网,看spring ioc的时候看spring容器扩展点的时候发现了beanpostprocessor 这个接口。下面是官方对它的详细描述:

          beanpostprocessor接口定义了回调方法,您可以实现提供自己的(或覆盖容器的默认)实例化逻辑,依赖性解析逻辑,等等。如果你想实现一些自定义逻辑spring容器实例化完成后,配置和初始化一个bean,您可以插入一个或多个beanpostprocessor实现。

          您可以配置多个beanpostprocessor实例,您可以控制的顺序执行这些beanpostprocessors通过设置属性。你可以设置这个属性只有beanpostprocessor实现命令接口;如果你写自己的beanpostprocessor你也应该考虑实现theordered接口。详情,请咨询beanpostprocessor的javadoc和命令接口。

          beanpostprocessor有两个方法postprocessbeforeinitialization,postprocessafterinitialization.如果一个对象实现了这个接口,那么就会在容器初始化init方法之前(就像initializingbean的afterpropertiesset()和其它公开的init方法)或在spring bean初始化之后执行回调。

          实现beanpostprocessor接口的类由容器是特殊而区别对待。所有beanpostprocessors和他们在启动时直接引用实例化bean,作为特殊的applicationcontext的启动阶段。接下来,所有beanpostprocessorsare注册分类的方式,适用于所有进一步bean容器。因为实现aop auto-proxying abeanpostprocessor本身,无论是beanpostprocessors还是beas他们有资格获得auto-proxying直接引用,因此没有方面编织进去。

          实现beanpostprocessor接口的类由容器是特殊而区别对待。所有beanpostprocessors和他们在启动时直接引用实例化bean,作为特殊的applicationcontext的启动阶段。接下来,所有beanpostprocessorsare注册分类的方式,适用于所有进一步bean容器。因为实现aop auto-proxying abeanpostprocessor本身,无论是beanpostprocessors还是beas他们有资格获得auto-proxying直接引用,因此没有方面编织进去。

          使用回调接口或注释与自定义实现beanpostprocessor是一种常见的扩展springioc容器。requiredannotationbeanpostprocessor是spring的一个例子 —— 一个实现beanpostprocessor附带的spring分布,确保javabean属性bean上标有一个(任意)注释(配置)会依赖注入值。

你说我一看到上面的aop这个spring两大特性之一我心里面都有一点小激动。后面他再来个spring的annotation一般也是用这个接口实现的。这下就忍不住了想去看一看requiredannotationbeanpostprocessor这个类到底干了什么。直接上源码

spring annotation support 
 
/* 
 * copyright 2002-2013 the original author or authors. 
 * 
 * licensed under the apache license, version 2.0 (the "license"); 
 * you may not use this file except in compliance with the license. 
 * you may obtain a copy of the license at 
 * 
 *   http://www.apache.org/licenses/license-2.0 
 * 
 * unless required by applicable law or agreed to in writing, software 
 * distributed under the license is distributed on an "as is" basis, 
 * without warranties or conditions of any kind, either express or implied. 
 * see the license for the specific language governing permissions and 
 * limitations under the license. 
 */ 
 
package org.springframework.beans.factory.annotation; 
 
import java.beans.propertydescriptor; 
import java.lang.annotation.annotation; 
import java.lang.reflect.method; 
import java.util.arraylist; 
import java.util.collections; 
import java.util.list; 
import java.util.set; 
import java.util.concurrent.concurrenthashmap; 
 
import org.springframework.beans.beansexception; 
import org.springframework.beans.propertyvalues; 
import org.springframework.beans.factory.beanfactory; 
import org.springframework.beans.factory.beanfactoryaware; 
import org.springframework.beans.factory.beaninitializationexception; 
import org.springframework.beans.factory.config.beandefinition; 
import org.springframework.beans.factory.config.configurablelistablebeanfactory; 
import org.springframework.beans.factory.config.instantiationawarebeanpostprocessoradapter; 
import org.springframework.beans.factory.support.mergedbeandefinitionpostprocessor; 
import org.springframework.beans.factory.support.rootbeandefinition; 
import org.springframework.core.conventions; 
import org.springframework.core.ordered; 
import org.springframework.core.priorityordered; 
import org.springframework.core.annotation.annotationutils; 
import org.springframework.util.assert; 
 
/** 
 * {@link org.springframework.beans.factory.config.beanpostprocessor} implementation 
 * that enforces required javabean properties to have been configured. 
 * 强制检测javabean必须的properties是否已经被配置 
 * required bean properties are detected through a java 5 annotation: 
 * 必须的bean属性通过java 5中的annotation自动检测到 
 * by default, spring's {@link required} annotation. 
 * 
 * <p>the motivation for the existence of this beanpostprocessor is to allow 
 * beanpostprocessor存在的意义是允许 
 * developers to annotate the setter properties of their own classes with an 
 * arbitrary jdk 1.5 annotation to indicate that the container must check 
 * for the configuration of a dependency injected value. this neatly pushes 
 * 开发人员注释setter属性与一个他们自己的类任意的jdk 1.5注释表明容器必须检查依赖注入的配置值。 
 * responsibility for such checking onto the container (where it arguably belongs), 
 * 这样就巧妙的把check的责任给了spring容器(它应该就属于的) 
 * and obviates the need (<b>in part</b>) for a developer to code a method that 
 * simply checks that all required properties have actually been set. 
 * 这样也就排除了开发人员需要编写一个简单的方法用来检测那么必须的properties是否已经设置了值 
 * <p>please note that an 'init' method may still need to implemented (and may 
 * still be desirable), because all that this class does is enforce that a 
 * 请注意初始化方法还是必须要实现的(并且仍然是可取的) 
 * 'required' property has actually been configured with a value. it does 
 * 因为所有这个class强制执行的是'required'属性是否已经被配置了值 
 * <b>not</b> check anything else... in particular, it does not check that a 
 * 它并不会check其实的事,特别的是,它不会check这个配置的值是不是null值 
 * configured value is not {@code null}. 
 * 
 * <p>note: a default requiredannotationbeanpostprocessor will be registered 
 * by the "context:annotation-config" and "context:component-scan" xml tags. 
 * 当你使用了"context:annotation-config"或者"context:component-scan"xml标签就会默认注册requiredannotationbeanpostprocessor 
 * remove or turn off the default annotation configuration there if you intend 
 * to specify a custom requiredannotationbeanpostprocessor bean definition. 
 * 你如果打算指定一个自定义的requiredannotationbeanpostprocessor的bean实现可以移除或者关闭默认的annotation配置 
 * 
 * @author rob harrop 
 * @author juergen hoeller 
 * @since 2.0 
 * @see #setrequiredannotationtype 
 * @see required 
 */ 
public class requiredannotationbeanpostprocessor extends instantiationawarebeanpostprocessoradapter 
    implements mergedbeandefinitionpostprocessor, priorityordered, beanfactoryaware { 
 
  /** 
   * bean definition attribute that may indicate whether a given bean is supposed 
   * to be skipped when performing this post-processor's required property check. 
   * 这个bean定义的属性表明当执行post-processor(后处理程序)这个check提供的bean的必须的属性 
   * @see #shouldskip 
   */ 
  public static final string skip_required_check_attribute = 
      conventions.getqualifiedattributename(requiredannotationbeanpostprocessor.class, "skiprequiredcheck"); 
 
 
  private class<? extends annotation> requiredannotationtype = required.class; 
 
  private int order = ordered.lowest_precedence - 1; 
 
  private configurablelistablebeanfactory beanfactory; 
 
  /** 
   * cache for validated bean names, skipping re-validation for the same bean 
   * 缓存已经确认过的bean名称,跳过后续同样的bean 
   */ 
  private final set<string> validatedbeannames = 
      collections.newsetfrommap(new concurrenthashmap<string, boolean>(64)); 
 
 
  /** 
   * set the 'required' annotation type, to be used on bean property 
   * setter methods. 
   * 设置所需的注释类型,使用bean属性setter方法 
   * <p>the default required annotation type is the spring-provided 
   * {@link required} annotation. 
   * 这个默认的required annotation类型是spring提供的annotation 
   * <p>this setter property exists so that developers can provide their own 
   * (non-spring-specific) annotation type to indicate that a property value 
   * is required. 
   * 这里设置这个property是为了开发者能够提供自己定义的annotaion类型用来表明这个属性值是必须的 
   */ 
  public void setrequiredannotationtype(class<? extends annotation> requiredannotationtype) { 
    assert.notnull(requiredannotationtype, "'requiredannotationtype' must not be null"); 
    this.requiredannotationtype = requiredannotationtype; 
  } 
 
  /** 
   * return the 'required' annotation type. 
   */ 
  protected class<? extends annotation> getrequiredannotationtype() { 
    return this.requiredannotationtype; 
  } 
 
  @override 
  public void setbeanfactory(beanfactory beanfactory) { 
    if (beanfactory instanceof configurablelistablebeanfactory) { 
      this.beanfactory = (configurablelistablebeanfactory) beanfactory; 
    } 
  } 
 
  public void setorder(int order) { 
    this.order = order; 
  } 
 
  @override 
  public int getorder() { 
    return this.order; 
  } 
 
 
  @override 
  public void postprocessmergedbeandefinition(rootbeandefinition beandefinition, class<?> beantype, string beanname) { 
  } 
 
  @override 
  public propertyvalues postprocesspropertyvalues( 
      propertyvalues pvs, propertydescriptor[] pds, object bean, string beanname) 
      throws beansexception { 
    // 利用缓存确定是否这个bean被validated 
    if (!this.validatedbeannames.contains(beanname)) { 
      // 不跳过 
      if (!shouldskip(this.beanfactory, beanname)) { 
        list<string> invalidproperties = new arraylist<string>(); 
        for (propertydescriptor pd : pds) { 
          // 如果被标记为了required 且 这个属性没有属性值(或其他处理条目) 
          if (isrequiredproperty(pd) && !pvs.contains(pd.getname())) { 
            // 增加这个属性 
            invalidproperties.add(pd.getname()); 
          } 
        } 
        // <span style="color:#ff0000;">如果无效的properties不为空。抛出异常</span> 
        if (!invalidproperties.isempty()) { 
          throw new beaninitializationexception(buildexceptionmessage(invalidproperties, beanname)); 
        } 
      } 
      // 把需要验证的bean名称添加进去 
      this.validatedbeannames.add(beanname); 
    } 
    return pvs; 
  } 
 
  /** 
   * check whether the given bean definition is not subject to the annotation-based 
   * required property check as performed by this post-processor. 
   * 通过post-processor(后处理程序)检测这个被给予的定义的bean是否受注释为基础的check必须的property的管束 
   * <p>the default implementations check for the presence of the 
   * {@link #skip_required_check_attribute} attribute in the bean definition, if any. 
   * 这个默认的实现check存在skip_required_check_attribute这个属性的定义的bean 
   * it also suggests skipping in case of a bean definition with a "factory-bean" 
   * reference set, assuming that instance-based factories pre-populate the bean. 
   * 它同样也建议跳过如果这个bean定义了"factory-bean"引用,假设那个基于实例的factories预先配置了bean 
   * @param beanfactory the beanfactory to check against 
   * @param beanname the name of the bean to check against 
   * @return {@code true} to skip the bean; {@code false} to process it 
   * 如果返回 true跳过这个bean,返回false就处理它 
   */ 
  protected boolean shouldskip(configurablelistablebeanfactory beanfactory, string beanname) { 
    // 如果这个beanfacotry为空或者这个bean工厂不包含一个给定名称的bean定义。返回false 
    if (beanfactory == null || !beanfactory.containsbeandefinition(beanname)) { 
      return false; 
    } 
    beandefinition beandefinition = beanfactory.getbeandefinition(beanname); 
    // 判断这个bean的工厂beanname,如果不为null,返回true 
    if (beandefinition.getfactorybeanname() != null) { 
      return true; 
    } 
    object value = beandefinition.getattribute(skip_required_check_attribute); 
    return (value != null && (boolean.true.equals(value) || boolean.valueof(value.tostring()))); 
  } 
 
  /** 
   * is the supplied property required to have a value (that is, to be dependency-injected)? 
   * 是否这个提供的必须的propery是否有一个值(这个是被依赖注入)? 
   * <p>this implementation looks for the existence of a 
   * {@link #setrequiredannotationtype "required" annotation} 
   * on the supplied {@link propertydescriptor property}. 
   * 这个实现是为了找到提供的proertydescriptor是提供了"required"注解 
   * @param propertydescriptor the target propertydescriptor (never {@code null}) 
   * @return {@code true} if the supplied property has been marked as being required; 
   * 返回true,如果提供的property已经被标记为必须的</span> 
   * {@code false} if not, or if the supplied property does not have a setter method 
   * 返回false,如果没有标记为必须的或者提供的property没有一个setter方法 
   */ 
  protected boolean isrequiredproperty(propertydescriptor propertydescriptor) { 
    method setter = propertydescriptor.getwritemethod(); 
    return (setter != null && annotationutils.getannotation(setter, getrequiredannotationtype()) != null); 
  } 
 
  /** 
   * build an exception message for the given list of invalid properties. 
   * 使用所给的异常properties来构建异常信息 
   * @param invalidproperties the list of names of invalid properties 
   * @param beanname the name of the bean 
   * @return the exception message 
   */ 
  private string buildexceptionmessage(list<string> invalidproperties, string beanname) { 
    int size = invalidproperties.size(); 
    stringbuilder sb = new stringbuilder(); 
    sb.append(size == 1 ? "property" : "properties"); 
    for (int i = 0; i < size; i++) { 
      string propertyname = invalidproperties.get(i); 
      if (i > 0) { 
        if (i == (size - 1)) { 
          sb.append(" and"); 
        } 
        else { 
          sb.append(","); 
        } 
      } 
      sb.append(" '").append(propertyname).append("'"); 
    } 
    sb.append(size == 1 ? " is" : " are"); 
    sb.append(" required for bean '").append(beanname).append("'"); 
    return sb.tostring(); 
  } 
 
} 

在上面的代码中所示。我们可以得出以下结论:

Spring Annotaion Support详细介绍及简单实例

上面已经把spring对于 org.springframework.beans.factory.annotation.required 这个标签的实现出来了。虽然只是一个小例子。但是我们可以根据spring以下的的包结构看到这是spring对于它自身annotation的很common的实现:

Spring Annotaion Support详细介绍及简单实例

从上面的例子中我可以看出spring对它本身的annotaion的一种实现。当前文中并没有讲述exception message是通过怎么传递的。但是这并不是本文讨论的范畴,有兴趣的朋友可以自己去看看。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!