最近正在看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(); 
  } 
 
} 

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

111

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

11

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

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

Spring Annotaion Support详细介绍及简单实例的更多相关文章

  1. Spring JdbcTemplate执行数据库操作详解

    JdbcTemplate是Spring框架自带的对JDBC操作的封装,目的是提供统一的模板方法使对数据库的操作更加方便、友好,效率也不错,这篇文章主要介绍了Spring JdbcTemplate执行数据库操作,需要的朋友可以参考下

  2. Spring Batch批处理框架操作指南

    Spring Batch 是 Spring 提供的一个数据处理框架。企业域中的许多应用程序需要批量处理才能在关键任务环境中执行业务操作,这篇文章主要介绍了Spring Batch批处理框架操作指南,需要的朋友可以参考下

  3. Spring详细讲解@Autowired注解

    @Autowired注解可以用在类属性,构造函数,setter方法和函数参数上,该注解可以准确地控制bean在何处如何自动装配的过程。在默认情况下,该注解是类型驱动的注入

  4. 使用Spring AOP实现用户操作日志功能

    这篇文章主要介绍了使用Spring AOP实现了用户操作日志功能,功能实现需要一张记录日志的log表,结合示例代码给大家讲解的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  5. Spring Security认证器实现过程详解

    一些权限框架一般都包含认证器和决策器,前者处理登陆验证,后者处理访问资源的控制,这篇文章主要介绍了Spring Security认证器实现过程,需要的朋友可以参考下

  6. spring学习JdbcTemplate数据库事务管理

    这篇文章主要为大家介绍了spring学习JdbcTemplate数据库事务管理,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  7. Spring Boot 集成Redisson实现分布式锁详细案例

    这篇文章主要介绍了Spring Boot 集成Redisson实现分布式锁详细案例,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下

  8. Spring Security实现接口放通的方法详解

    在用Spring Security项目开发中,有时候需要放通某一个接口时,我们需要在配置中把接口地址配置上,这样做有时候显得麻烦。本文将通过一个注解的方式快速实现接口放通,感兴趣的可以了解一下

  9. 如何利用Spring把元素解析成BeanDefinition对象

    这篇文章主要介绍了如何利用Spring把元素解析成BeanDefinition对象,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下

  10. Spring解决循环依赖问题及三级缓存的作用

    这篇文章主要介绍了Spring解决循环依赖问题及三级缓存的作用,所谓的三级缓存只是三个可以当作是全局变量的Map,Spring的源码中大量使用了这种先将数据放入容器中等使用结束再销毁的代码风格

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部