Spring 注解大全与详解

8,651 阅读41分钟

这里主要是对spring中注释的含义、参数进行介绍

  • @Component

  1. 含义

  表示带注释的类是“组件”。当使用基于注释的配置和类路径扫描时,这些类被视为自动检测的候选者。
  相当于在配置文件中配置bean。

<bean id="student" class="com.yellowdoge.hxl.model.Student">
    <property name="name" value="hxl"></property>
    <property name="age" value="19"></property>
</bean>
  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Component {
    String value() default "";
}

  参数value的默认值为“”,如果传了值那么这个值就是该类在spring容器中的id,默认情况下id为该类名称首字母小写。假设一个类的名字为Student,使用了默认参数,它的id就应该是student。

  • @Repository

  1. 含义

  表示带注释的类是“存储库”,最初由域驱动设计(Evans,2003)定义为“用于封装模拟对象集合的存储,检索和搜索行为的机制”。
  实现传统Java EE模式(如“数据访问对象”)的团队也可以将此构造型应用于DAO类,但在此之前应注意理解数据访问对象和DDD样式存储库之间的区别。
  在注解了@Repository的类上如果数据库操作中抛出了异常,就能对其进行处理,转而抛出的是翻译后的spring专属数据库异常,方便我们对异常进行排查处理。
  从Spring 2.5开始,这个注释也可以作为一个特化@Component,允许通过类路径扫描自动检测实现类。

  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
    String value() default "";
}

  参数value的默认值为“”,如果传了值那么这个值就是该类在spring容器中的id,默认情况下id为该类名称首字母小写。假设一个类的名字为StudentDao,使用了默认参数,它的id就应该是studentDao。

  • @Controller

  1. 含义

  表示带注释的类是“控制器”(例如Web控制器)。此注释用作特殊化@Component,允许通过类路径扫描自动检测实现类。它通常与基于RequestMapping注释的带注释的处理程序方法结合使用 。

  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
    String value() default "";
}

  参数value的默认值为“”,如果传了值那么这个值就是该类在spring容器中的id,默认情况下id为该类名称首字母小写。假设一个类的名字为StudentController,使用了默认参数,它的id就应该是studentController。

  • @Service

  1. 含义

  表示带注释的类是“服务”,最初由域驱动设计(Evans,2003)定义为“作为模型中独立的接口提供的操作,没有封装状态”。
  也可能表明一个类是“Business Service Facade”(在核心J2EE模式意义上)或类似的东西。
  此注释用作特殊化@Component,允许通过类路径扫描自动检测实现类。

  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
    String value() default "";
}

  参数value的默认值为“”,如果传了值那么这个值就是该类在spring容器中的id,默认情况下id为该类名称首字母小写。假设一个类的名字为StudentService,使用了默认参数,它的id就应该是studentService。

  • @Autowired

  1. 含义

  枚举确定自动装配状态:即,bean是否应该使用setter注入由Spring容器自动注入其依赖项。@Autowired默认是按照类型装配注入的。这是Spring DI的核心概念。
  可用于基于注释的配置,例如AspectJ AnnotationBeanConfigurer方面。

  1. 参数

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, > > ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
    boolean required() default true;
}

  参数required的默认值为true,表示在默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用,如下:

@Autowired() 
@Qualifier("baseDao")     
private BaseDao baseDao;    
  • @Resource

  1. 含义

  这是jsr250规范的实现,@Resource通过 “CommonAnnotationBeanPostProcessor” 类实现依赖注入。   @Resource标记应用程序所需的资源。此注释可以应用于应用程序组件类,或应用于组件类的字段或方法。
  当注释应用于字段或方法时,容器将在初始化组件时将所请求资源的实例注入应用程序组件。 如果注释应用于组件类,则应用程序会在运行时寻找资源。
  即使此注释未标记为继承,也需要部署工具检查任何组件类的所有超类,以发现此注释在所有超类中的所有用法。 所有这些注释实例都指定应用程序组件所需的资源。
  请注意,此注释可能出现在超类的私有字段和方法上;在这些情况下,容器也需要进行注射。

  1. 参数

@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface Resource {
    /**
     * The JNDI name of the resource.  For field annotations,
     * the default is the field name.  For method annotations,
     * the default is the JavaBeans property name corresponding
     * to the method.  For class annotations, there is no default
     * and this must be specified.
     */
    String name() default "";

   /**
     * The name of the resource that the reference points to. It can
     * link to any compatible resource using the global JNDI names.
     *
     * @since Common Annotations 1.1
     */

    String lookup() default "";

    /**
     * The Java type of the resource.  For field annotations,
     * the default is the type of the field.  For method annotations,
     * the default is the type of the JavaBeans property.
     * For class annotations, there is no default and this must be
     * specified.
     */
    Class<?> type() default java.lang.Object.class;

    /**
     * The two possible authentication types for a resource.
     */
    enum AuthenticationType {
            CONTAINER,
            APPLICATION
    }

    /**
     * The authentication type to use for this resource.
     * This may be specified for resources representing a
     * connection factory of any supported type, and must
     * not be specified for resources of other types.
     */
    AuthenticationType authenticationType() default AuthenticationType.CONTAINER;

    /**
     * Indicates whether this resource can be shared between
     * this component and other components.
     * This may be specified for resources representing a
     * connection factory of any supported type, and must
     * not be specified for resources of other types.
     */
    boolean shareable() default true;

    /**
     * A product specific name that this resource should be mapped to.
     * The name of this resource, as defined by the <code>name</code>
     * element or defaulted, is a name that is local to the application
     * component using the resource.  (It's a name in the JNDI
     * <code>java:comp/env</code> namespace.)  Many application servers
     * provide a way to map these local names to names of resources
     * known to the application server.  This mapped name is often a
     * <i>global</i> JNDI name, but may be a name of any form. <p>
     *
     * Application servers are not required to support any particular
     * form or type of mapped name, nor the ability to use mapped names.
     * The mapped name is product-dependent and often installation-dependent.
     * No use of a mapped name is portable.
     */
    String mappedName() default "";

    /**
     * Description of this resource.  The description is expected
     * to be in the default language of the system on which the
     * application is deployed.  The description can be presented
     * to the Deployer to help in choosing the correct resource.
     */
    String description() default "";
}

  参数name的默认值为“”,表示资源的jndi名称。当注释的字段时,就为字段名称;当注释的方法时,就为java beans的名称;当注释的类时,没有默认值,必须声明name的值。
  参数lookup的默认值为“”,表示资源名称的参考点,它可以使用全局JNDI名称链接到任何兼容的资源。
  参数type的默认值是java.lang.Object.class,表示资源的java类型。当注释的字段时,就为字段对应的类型;当注释的方法时,就为java beans的java类型;当注释的类时,没有默认值,必须声明type的值。
  参数authenticationType的默认值为AuthenticationType.CONTAINER,表示任何受支持类型的连接工厂的资源指定此方法,不得为其他类型的资源指定。   参数shareable的默认值为true,表示两个组件之间是否共享此资源,任何受支持类型的连接工厂的资源指定此方法,不得为其他类型的资源指定。
  参数mappedName的默认值为“”,表示资源映射到的特定产品的名称。资源的名称使用name元素或默认定义,则该名称是本地应用组件的使用名称(命名空间:java:comp/env)。许多应用程序服务器都提供一种方式将这些本地名称映射到应用程序服务器已知的资源名称。此映射的名称通常是全局JNDI名称,但也可以是任何形式的名称。应用程序服务器不需要支持任何特殊形式或类型的映射名称,也不需要具有使用映射名称的能力。
  参数description的默认值为“”,表示资源的描述(应用程序的系统的默认语言)。

  • @Inject

  1. 含义

  这是jsr330中的规范,通过‘AutowiredAnnotationBeanPostProcessor’ 类实现的依赖注入。属于类型注入。

  1. 参数

@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Inject {
}

  @Inject没有参数,但是和它有个常用搭配。如下是@Inject的使用,不加@Named注解,需要配置与变量名一致即可。   

@Inject
@Named("mongo")
private Mongo mongo;
  • @Configuration

  1. 含义

  @Configuration是把一个类变成一个配置类,即在这个类中可以用@Bean标识方法,并且把方法返回的对象加入到spring容器中,并且返回的是同一个实例。
  配置类必须以类的形式提供(不能是工厂方法返回的实例),允许通过生成子类在运行时增强(cglib 动态代理)。配置类不能是 final 类(没法动态代理)。配置注解通常为了通过 @Bean 注解生成 Spring 容器管理的类。配置类必须是非本地的(即不能在方法中声明,不能是 private)。任何嵌套配置类都必须声明为static。@Bean 方法可能不会反过来创建进一步的配置类(也就是返回的 bean 如果带有@Configuration,也不会被特殊处理,只会作为普通的 bean)。

  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
    String value() default "";
}

  参数value的默认值为“”,如果传了值那么这个值就是该类在spring容器中的id,默认情况下id为该类名称首字母小写。假设一个类的名字为StudentConfiguration,使用了默认参数,它的id就应该是studentConfiguration。

  • @ComponentScan

  1. 含义

  @ComponentScan主要是定义扫描的路径并从中找出标识了需要装配的类自动装配到spring的bean容器中。

  1. 参数

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan {
    @AliasFor("basePackages")
    String[] value() default {};

    @AliasFor("value")
    String[] basePackages() default {};

    Class<?>[] basePackageClasses() default {};

    Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;

    Class<? extends ScopeMetadataResolver> scopeResolver() default AnnotationScopeMetadataResolver.class;

    ScopedProxyMode scopedProxy() default ScopedProxyMode.DEFAULT;

    String resourcePattern() default "**/*.class";

    boolean useDefaultFilters() default true;

    ComponentScan.Filter[] includeFilters() default {};

    ComponentScan.Filter[] excludeFilters() default {};

    boolean lazyInit() default false;

    @Retention(RetentionPolicy.RUNTIME)
    @Target({})
    public @interface Filter {
        FilterType type() default FilterType.ANNOTATION;

        @AliasFor("classes")
        Class<?>[] value() default {};

        @AliasFor("value")
        Class<?>[] classes() default {};

        String[] pattern() default {};
    }
}

  参数value别名basePackages,默认值为空的String数组,String数组中的路径会被扫描并把标识了需要装配的类自动装配到spring的bean容器中。value和basePackages不能同时设置。
  参数basePackages别名value,默认值为空的String数组,String数组中的路径会被扫描并把标识了需要装配的类自动装配到spring的bean容器中。value和basePackages不能同时设置。
  参数basePackageClasses默认值为空的java Class数组。在数组中指定具体的扫描的类。
  参数nameGenerator指定对应的bean名称的生成器,默认的是BeanNameGenerator。
  参数scopeResolver指定对应的处理检测到bean的scope范围处理类,默认的是AnnotationScopeMetadataResolver。
  参数scopedProxy指定代理模式,默认为ScopedProxyMode.DEFAULT。下面是ScopedProxyMode枚举类。   

public enum ScopedProxyMode {
    DEFAULT,
    NO,
    INTERFACES,
    TARGET_CLASS;

    private ScopedProxyMode() {
    }
}

  参数resourcePattern默认值为“**/*.class”,在这里可以配置正则表达式以此来选择想要扫描的所有指定的包路径下的类。
  参数useDefaultFilters表示是否对带有@Component @Repository @Service @Controller注解的类开启检测,默认是开启的。
  参数includeFilters表示哪些类型符合组件扫描的条件。FilterType有5种类型如:

  • ANNOTATION, 注解类型 默认
  • ASSIGNABLE_TYPE,指定固定类
  • ASPECTJ,ASPECTJ类型
  • REGEX,正则表达式
  • CUSTOM,自定义类型

  参数excludeFilters表示哪些类型不符合组件扫描的条件。
  参数lazyInit表示是否应注册扫描的bean以进行延迟初始化。默认是不开启。
  

  • @Bean

  1. 含义

  @Bean用于注释方法,表示该方法返回的Bean会被放入spring容器中。

  1. 参数

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {
    @AliasFor("name")
    String[] value() default {};

    @AliasFor("value")
    String[] name() default {};

    Autowire autowire() default Autowire.NO;

    String initMethod() default "";

    String destroyMethod() default "(inferred)";
}

  参数value别名name,默认值为空的String数组,String数组中的名称都会变成这个bean的id。value和name不能同时设置。
  参数name别名value,默认值为空的String数组,String数组中的名称都会变成这个bean的id。value和name不能同时设置。
  参数autowire表示是否通过名称或类型的约定自动装配注入依赖项。
  参数initMethod表示初始化期间调用bean实例的方法的可选名称。
  参数destroyMethod表示关闭应用程序上下文时调用bean实例的方法的可选名称。
  

  • @Aspect

  1. 含义

  @Aspect的作用是把当前类标识为一个切面类供容器读取。

  1. 参数

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Aspect {
    String value() default "";
}

  参数value默认值为“”,表示这个类在spring容器中的id。

  • @After

  1. 含义

  final增强,不管是抛出异常或者正常退出都会执行。

  1. 参数

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface After {
    String value();

    String argNames() default "";
}

  参数value无默认值,必须声明,用于指定方法,在指定方法执行结束时执行@After注释的方法。
  参数argNames默认值为“”,argNames属性是用于指定在表达式中应用的参数名与Advice方法参数是如何对应的,argNames中指定的参数名必须与表达式中的一致,可以与Advice方法参数名不一致;当表达式中使用了多个参数时,argNames中需要指定多个参数,多个参数之间以英文逗号分隔,这些参数的顺序必须与对应的Advice方法定义的参数顺序是一致的。。

  • @Before

  1. 含义

  标识一个前置增强方法,相当于BeforeAdvice的功能。

  1. 参数

  

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Before {
    String value();

    String argNames() default "";
}

  参数value无默认值,必须声明,用于指定方法,在指定方法执行前执行@After注释的方法。
  参数argNames默认值为“”,argNames属性是用于指定在表达式中应用的参数名与Advice方法参数是如何对应的,argNames中指定的参数名必须与表达式中的一致,可以与Advice方法参数名不一致;当表达式中使用了多个参数时,argNames中需要指定多个参数,多个参数之间以英文逗号分隔,这些参数的顺序必须与对应的Advice方法定义的参数顺序是一致的。。
  

  • @Around

  1. 含义

  环绕增强,相当于MethodInterceptor。

  1. 参数

  

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Around {
    String value();

    String argNames() default "";
}

  参数value无默认值,必须声明,用于指定方法,相当于把指定的方法插入到@After注释的方法中执行。
  参数argNames默认值为“”,argNames属性是用于指定在表达式中应用的参数名与Advice方法参数是如何对应的,argNames中指定的参数名必须与表达式中的一致,可以与Advice方法参数名不一致;当表达式中使用了多个参数时,argNames中需要指定多个参数,多个参数之间以英文逗号分隔,这些参数的顺序必须与对应的Advice方法定义的参数顺序是一致的。。
  

  • @PointCut(AspectJ)

  1. 含义

  声明一个切入点。    2. ### 参数

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface PointCut {
    String value() default "";

    String argNames() default "";
}

  参数value默认值为“”,用于指定截取的方法。并且可以把注释的方法名字当做签名供@Around、@Before、@After等Advice方法使用。
  参数argNames默认值为“”,argNames属性是用于指定在表达式中应用的参数名与Advice方法参数是如何对应的,argNames中指定的参数名必须与表达式中的一致,可以与Advice方法参数名不一致;当表达式中使用了多个参数时,argNames中需要指定多个参数,多个参数之间以英文逗号分隔,这些参数的顺序必须与对应的Advice方法定义的参数顺序是一致的。。
  

  • @Transactional

  1. 含义

  描述方法或类的事务属性。
  这个注释类型通常可以直接与Spring的RuleBasedTransactionAttribute 类相媲美 ,实际上它AnnotationTransactionAttributeSource会直接将数据转换为后一个类,因此Spring的事务支持代码不必知道注释。如果没有规则相关的例外,它会像对待 DefaultTransactionAttribute (回滚到RuntimeException和Error,但不会对检查的异常)。

  1. 参数

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Transactional {
    @AliasFor("transactionManager")
    String value() default "";

    @AliasFor("value")
    String transactionManager() default "";

    Propagation propagation() default Propagation.REQUIRED;

    Isolation isolation() default Isolation.DEFAULT;

    int timeout() default -1;

    boolean readOnly() default false;

    Class<? extends Throwable>[] rollbackFor() default {};

    String[] rollbackForClassName() default {};

    Class<? extends Throwable>[] noRollbackFor() default {};

    String[] noRollbackForClassName() default {};
}

  参数value的别名为transactionManager,默认值为“”,可选的限定描述符,指定使用的事务管理器。value和transactionManager不能同时指定。
  参数transactionManager的别名为value,默认值为“”,可选的限定描述符,指定使用的事务管理器。value和transactionManager不能同时指定。
  参数propagation设置事务传播行为。
  参数isolation设置事务隔离级别。
  参数timeout设置事务超时时间。
  参数readOnly设置事务是否只读,默认读写。
  参数rollbackFor设置导致事务回滚的异常类数组。
  参数rollbackForClassName设置导致事务回滚的异常类名字数组。
  参数noRollbackFor设置不会导致事务回滚的异常类数组。
  参数noRollbackForClassName设置不会导致事务回滚的异常类名字数组。

  • @Cacheable

  1. 含义

  注释指示可以缓存调用方法(或类中的所有方法)的结果。
  每次调用一个建议的方法时,都会应用缓存行为,检查是否已经为给定的参数调用了该方法。合理的默认值只是使用方法参数来计算键,但可以通过key()属性提供SpEL表达式,或者自定义 KeyGenerator实现可以替换默认值(请参阅参考资料keyGenerator())。
  如果在计算键的高速缓存中未找到任何值,则将调用目标方法并将返回的值存储在关联的高速缓存中。请注意,Java8的Optional返回类型会自动处理,其内容存储在缓存中(如果存在)。
  此注释可用作元注释,以创建具有属性覆盖的自定义组合注释。

  1. 参数

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Cacheable {
    @AliasFor("cacheNames")
    String[] value() default {};

    @AliasFor("value")
    String[] cacheNames() default {};

    String key() default "";

    String keyGenerator() default "";

    String cacheManager() default "";

    String cacheResolver() default "";

    String condition() default "";

    String unless() default "";

    boolean sync() default false;
}

  参数value的别名为cacheNames,默认值为空的String数组,指定存储方法调用结果的高速缓存的名称。value和cacheNames不能同时指定。
  参数cacheNames的别名为value,默认值为空的String数组,指定存储方法调用结果的高速缓存的名称。value和cacheNames不能同时指定。
  参数key为用于动态计算密钥的Spring Expression Language(SpEL)表达式。如果不指定,则缺省按照方法的所有参数进行组合。
  参数keyGenerator用于指定要使用的自定义KeyGenerator的bean名称。
  参数cacheManager默认值为“”,在未设置CacheManager的情况下用于指定自定义CacheManager的bean的名称。
  参数cacheResolver默认值为“”,用于指定自定义的CacheResolver的bean的名称。
  参数condition使用Spring Expression Language(SpEL)表达式,用于指定方法缓存条件。
  参数unless使用Spring Expression Language(SpEL)表达式,用于指定否决方法缓存条件。
  参数sync表示当多个线程正在尝试加载同一个键的值,是否同步基础方法的调用。默认为不同步。

  • @EnableAspectJAutoProxy

  1. 含义

  支持处理使用AspectJ @Aspect注释标记的组件,类似于Spring的aop:aspectj-autoproxyXML元素中的功能。一般和@Configuration一起使用。

  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({AspectJAutoProxyRegistrar.class})
public @interface EnableAspectJAutoProxy {
    boolean proxyTargetClass() default false;

    boolean exposeProxy() default false;
}

  参数proxyTargetClass指示是否要创建基于子类的(CGLIB)代理而不是基于标准Java接口的代理。
  参数exposeProxy指示代理是否应由AOP框架公开,作为ThreadLocal 以便通过AopContext类进行检索。

  • @Value

  1. 含义

  字段或方法/构造函数参数级别的注释,指示受影响参数的默认值表达式。
  通常用于表达式驱动的依赖注入。还支持动态解析处理程序方法参数,例如在Spring MVC中。
  常见的用例是使用“#{systemProperties.myProp}”样式表达式分配默认字段值。

  1. 参数

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
    String value();
}

  参数value没有默认值,必须声明。参数为Spel表达式。

  • @PropertySource

  1. 含义

  注释提供了一个方便的声明机制,用于添加一个PropertySource到Spring的 Environment。与@Configuration一起使用。

  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {
    String name() default "";

    String[] value();

    boolean ignoreResourceNotFound() default false;

    String encoding() default "";

    Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;
}

  参数name默认值为“”,指定此属性源的名称。
  参数value无默认值,必须声明。指示要加载的属性文件的资源位置。
  参数ignoreResourceNotFound指示当property resource未找到时是否忽略。
  参数encoding给定资源的特定字符编码。
  参数factory指定自定义PropertySourceFactory。

  • @PostConstruct

  1. 含义

  被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。

  1. 参数

@Documented
@Retention (RUNTIME)
@Target(METHOD)
public @interface PostConstruct {
}

  无参数。

  • @PreDestroy

  1. 含义

  PreDestroy()方法在destroy()方法之后执行。

  1. 参数

@Documented
@Retention (RUNTIME)
@Target(METHOD)
public @interface PreDestroy {
}

  无参数。

  • @Profile

  1. 含义

  表示当一个或多个指定的文件处于活动状态时,这个组件是有资格注册的。使用@Profile注解类或者方法,达到在不同情况下选择实例化不同的Bean。@Profile(“dev”)表示当环境为dev时实例化。

  1. 参数

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({ProfileCondition.class})
public @interface Profile {
    String[] value();
}

  参数value无默认值,必须声明。表示组件可以被注册时的profiles集合。

  • @EnableAsync

  1. 含义

  启用Spring的异步方法执行功能,类似于Spring的task:*XML命名空间中的功能。 要与@Configuration一起使用。

  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({AsyncConfigurationSelector.class})
public @interface EnableAsync {
    Class<? extends Annotation> annotation() default Annotation.class;

    boolean proxyTargetClass() default false;

    AdviceMode mode() default AdviceMode.PROXY;

    int order() default 2147483647;
}

  参数annotation指示要在类或方法级别检测的“异步”注释类型。
  参数proxyTargetClass指示是否要创建基于子类的(CGLIB)代理而不是基于标准Java接口的代理。
  参数mode指定应如何应用异步通知。AdviceMode有两种类型:

  • PROXY
  • ASPECTJ

  参数order指出AsyncAnnotationBeanPostProcessor应该应用的顺序。值小的优先。

  • @Async

  1. 含义

  将方法标记为异步执行候选的注释。也可以在class级别使用,在这种情况下,所有类型的方法都被视为异步。
  就目标方法签名而言,支持任何参数类型。但是,返回类型被限制为void或者 Future。在后一种情况下,您可以声明更具体的类型ListenableFuture或 CompletableFuture类型,以允许与异步任务进行更丰富的交互,并通过进一步的处理步骤立即组合。
  Future从代理返回的句柄将是一个实际的异步 Future,可用于跟踪异步方法执行的结果。但是,由于目标方法需要实现相同的签名,因此必须返回一个临时Future句柄,该句柄只传递一个值:例如Spring AsyncResult,EJB 3.1 AsyncResult或者CompletableFuture.completedFuture(Object)。

  1. 参数

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Async {
    String value() default "";
}

  参数value默认值为“”,指定异步操作的限定符值。

  • @EnableScheduling

  1. 含义

  启用Spring的计划任务执行功能,类似于Spring的task:*XML命名空间中的功能。要在和@Configuration一同使用。

  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Import({SchedulingConfiguration.class})
@Documented
public @interface EnableScheduling {
}

  无参数。

  • @Scheduled

  1. 含义

  用于标记一个需要定期执行的方法。cron(),fixedDelay()或fixedRate()中的至少一个属性必须指定参数。
  带注释的方法必须没有参数。它通常会有一个void返回类型; 如果不是,则通过调度程序调用时将忽略返回的值。
  通过注册ScheduledAnnotationBeanPostProcessor来执行@Scheduled注释的处理。这可以手动完成,也可以通过<task:annotation-driven />元素或@EnableScheduling注释更方便地完成。
  此注释可用作元注释,以创建具有属性覆盖的自定义组合注释。

  1. 参数

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {
    String cron() default "";

    String zone() default "";

    long fixedDelay() default -1L;

    String fixedDelayString() default "";

    long fixedRate() default -1L;

    String fixedRateString() default "";

    long initialDelay() default -1L;

    String initialDelayString() default "";
}

  参数cron是一个类似cron的表达式,扩展了通常的UN * X定义,包括第二个以及分钟,小时,星期几,月和星期几的触发器。
  参数zone表示解析cron表达式的时区。
  参数fixedDelay设置在上一次调用结束和下一次调用开始之间以固定周期(以毫秒为单位)执行带注释的方法。
  参数fixedDelayString设置在上一次调用结束和下一次调用开始之间以固定周期(以毫秒为单位)执行带注释的方法。
  参数fixedRate设置在上一次调用开始和下一次调用开始之间以固定的周期(以毫秒为单位)执行带注释的方法。
  参数fixedRateString设置在上一次调用开始和下一次调用开始之间以固定的周期(以毫秒为单位)执行带注释的方法。
  参数initialDelay设置在第一次执行fixedRate()或fixedDelay()任务之前延迟的毫秒数 。
  参数initialDelayString设置在第一次执行fixedRate()或fixedDelay()任务之前延迟的毫秒数 。

  • @Conditional

  1. 含义

  表示只有在所有指定条件匹配时,组件才有资格进行注册。
  任何可以通过编程确定在bean被注册之前的状态(见任何状态Condition的详细信息)都可以是条件。

  1. 参数

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
    Class<? extends Condition>[] value();
}

  参数value无默认值,必须声明。参数类型为实现了Condition接口的class。

  • @Enable*

  1. 含义

  @enable*是springboot中用来启用某一个功能特性的一类注解。其中包括我们常用的@SpringBootApplication注解中用于开启自动注入的annotation @EnableAutoConfiguration,开启异步方法的annotation @EnableAsync,开启将配置文件中的属性以bean的方式注入到IOC容器的annotation@EnableConfigurationProperties等。

  • @RunWith

  1. 含义

  JUnit用例都是在Runner(运行器)来执行的。通过它,可以为这个测试类指定一个特定的Runner。

  1. 参数

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Inherited
public @interface RunWith {
    Class<? extends Runner> value();
}

  参数value无默认值,必须声明。参数类型为实现了Runner接口的class。
  常用Runner类有:

  • JUnit4.class

  • SpringJUnit4ClassRunner.class

  • Suite.class

  • Parameterized.class

  • Categories.class

  • Theories.class

  • @ContextConfiguration

  1. 含义

  @ContextConfiguration定义class级元数据,用于确定如何加载和配置ApplicationContext集成测试。
  在Spring 3.1之前,仅支持基于路径的资源位置(通常是XML配置文件)。在Spring 3.1中,背景装载机可以选择支持任何基于路径或基于类的资源。在Spring 4.0.4中,上下文装载机可以选择支持基于路径 和同时基于类的资源。因此 @ContextConfiguration可用于声明基于路径的资源位置(通过locations()或value()属性)或带 注释的类(通过classes()属性)。但请注意,大多数实现SmartContextLoader仅支持单一资源类型。从Spring 4.1开始,基于路径的资源位置可以是XML配置文件或Groovy脚本(如果Groovy在类路径上)。当然,第三方框架可以选择支持其他类型的基于路径的资源。

  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface ContextConfiguration {
    @AliasFor("locations")
    String[] value() default {};

    @AliasFor("value")
    String[] locations() default {};

    Class<?>[] classes() default {};

    Class<? extends ApplicationContextInitializer<?>>[] initializers() default > {};

    boolean inheritLocations() default true;

    boolean inheritInitializers() default true;

    Class<? extends ContextLoader> loader() default ContextLoader.class;

    String name() default "";
}

  参数value别名locations,默认值为空String字符数组。用于指定加载ApplicationContext的资源位置 。value和locations不能同时设置。
  参数locations别名value,默认值为空String字符数组。用于指定加载ApplicationContext的资源位置 。value和locations不能同时设置。
  参数classes用于指定加载ApplicationContext的注释类。
  参数initializers指定用于初始化ConfigurableApplicationContext的程序上下文初始化类。
  参数inheritLocations设置是否应继承测试超类中的resource locations或注释类。
  参数inheritInitializers设置是否应继承来自测试超类的上下文初始值设定项。
  参数name设置这个配置的上下文层次结构级别的名称。

  • @ActiveProfiles

  1. 含义

  @ActiveProfiles是一个class级别注释,用于声明在加载 ApplicationContext来测试时应使用哪些活动Bean定义配置文件。

  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface ActiveProfiles {
    @AliasFor("profiles")
    String[] value() default {};

    @AliasFor("value")
    String[] profiles() default {};

    Class<? extends ActiveProfilesResolver> resolver() default ActiveProfilesResolver.class;

    boolean inheritProfiles() default true;
}

  参数value别名profiles,默认值为空String字符数组。用于指定要激活的bean定义配置文件。value和profiles不能同时设置。
  参数profiles别名value,默认值为空String字符数组。用于指定要激活的bean定义配置文件。value和profiles不能同时设置。
  参数resolver指定用于处理bean定义配置文件的ActiveProfilesResolver。
  参数inheritProfiles设置是否应继承超类中的bean定义配置文件 。

  • @EnableWebMvc

  1. 含义

  将此注释添加到带有@Configuration的类中会从WebMvcConfigurationSupport中导入Spring MVC配置。
  要自定义导入的配置,请实现接口WebMvcConfigurer并重写要自定义的方法。

  1. 参数

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({DelegatingWebMvcConfiguration.class})
public @interface EnableWebMvc {
}

  无参数。

  • @RequestMapping

  1. 含义

  使用灵活方法签名将Web请求映射到请求处理类中的方法的注释。

  1. 参数

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
    String name() default "";

    @AliasFor("path")
    String[] value() default {};

    @AliasFor("value")
    String[] path() default {};

    RequestMethod[] method() default {};

    String[] params() default {};

    String[] headers() default {};

    String[] consumes() default {};

    String[] produces() default {};
}

  参数name默认值为“”。用于指定该映射的名称。
  参数value别名path。用于指定映射的一个或者多个路由。value和profiles不能同时设置。
  参数path别名value。用于指定映射的一个或者多个路由。value和profiles不能同时设置。
  参数method用于指定该映射响应的请求的方法,缩小映射范围,包括GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE。
  参数params用于指定该映射响应的请求的参数,缩小映射范围,可以实现多个方法处理同一个URL。
  参数headers用于指定该映射响应的请求的消息头,缩小映射范围。
  

http请求报文
  参数consumes用于指定该映射响应的请求的Content-Type,缩小映射范围。
  参数produces用于指定该映射响应的请求的Accept,缩小映射范围。

  • @GetMapping

  1. 含义

  用于将GET类型的HTTP请求映射到特定处理方法的注释。
  具体来说,@GetMapping是一个作为快捷方式的组合注释@RequestMapping(method = RequestMethod.GET)。

  1. 参数

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(
    method = {RequestMethod.GET}
)
public @interface GetMapping {
    @AliasFor(
        annotation = RequestMapping.class
    )
    String name() default "";

    @AliasFor(
        annotation = RequestMapping.class
    )
    String[] value() default {};

    @AliasFor(
        annotation = RequestMapping.class
    )
    String[] path() default {};

    @AliasFor(
        annotation = RequestMapping.class
    )
    String[] params() default {};

    @AliasFor(
        annotation = RequestMapping.class
    )
    String[] headers() default {};

    @AliasFor(
        annotation = RequestMapping.class
    )
    String[] consumes() default {};

    @AliasFor(
        annotation = RequestMapping.class
    )
    String[] produces() default {};
}

  参数name别名RequestMapping.name(),作用同RequestMapping.name。
  参数value别名RequestMapping.value(),作用同RequestMapping.value。
  参数path别名RequestMapping.path(),作用同RequestMapping.path。
  参数params别名RequestMapping.params(),作用同RequestMapping.params。
  参数headers别名RequestMapping.headers(),作用同RequestMapping.headers。
  参数consumes别名RequestMapping.consumes(),作用同RequestMapping.consumes。
  参数produces别名RequestMapping.produces(),作用同RequestMapping.produces。

  • @PostMapping

  1. 含义

  用于将POST类型的HTTP请求映射到特定处理方法的注释。
  具体来说,@PostMapping是一个作为快捷方式的组合注释@RequestMapping(method = RequestMethod.POST)。

  1. 参数

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(
    method = {RequestMethod.POST}
)
public @interface PostMapping {
    @AliasFor(
        annotation = RequestMapping.class
    )
    String name() default "";

    @AliasFor(
        annotation = RequestMapping.class
    )
    String[] value() default {};

    @AliasFor(
        annotation = RequestMapping.class
    )
    String[] path() default {};

    @AliasFor(
        annotation = RequestMapping.class
    )
    String[] params() default {};

    @AliasFor(
        annotation = RequestMapping.class
    )
    String[] headers() default {};

    @AliasFor(
        annotation = RequestMapping.class
    )
    String[] consumes() default {};

    @AliasFor(
        annotation = RequestMapping.class
    )
    String[] produces() default {};
}

  参数name别名RequestMapping.name(),作用同RequestMapping.name。
  参数value别名RequestMapping.value(),作用同RequestMapping.value。
  参数path别名RequestMapping.path(),作用同RequestMapping.path。
  参数params别名RequestMapping.params(),作用同RequestMapping.params。
  参数headers别名RequestMapping.headers(),作用同RequestMapping.headers。
  参数consumes别名RequestMapping.consumes(),作用同RequestMapping.consumes。
  参数produces别名RequestMapping.produces(),作用同RequestMapping.produces。

  • @ResponseBody

  1. 含义

  该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。
  从版本4.0开始,此注释也可以添加到类型级别,在这种情况下,它是继承的,不需要在方法级别添加。

  1. 参数

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ResponseBody {
}

  无参数。

  • @RequestBody

  1. 含义

  该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上。
  再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。

  1. 参数

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestBody {
    boolean required() default true;
}

  参数required设置body部分数据是否必需。同@Autowired.required。

  • @PathVariable

  1. 含义

  当使用@RequestMapping URI占位符映射时,Url中可以通过一个或多个{xxxx}占位符映射,通过@PathVariable可以绑定占位符参数到方法参数中。

  1. 参数

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PathVariable {
    @AliasFor("name")
    String value() default "";

    @AliasFor("value")
    String name() default "";

    boolean required() default true;
}

  参数value别名name,默认值为“”。用于指定要绑定的路径变量的名称。value和name不能同时设置。
  参数name别名value,默认值为“”。用于指定要绑定的路径变量的名称。value和name不能同时设置。
  参数required设置是否需要路径变量。默认为需要。

  • @RestController

  1. 含义

  组合了@Controller和@ResponseBody的注释。
  带有此注释的类型被视为控制器,其中@RequestMapping和@ResponseBody采用默认设置。

  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    String value() default "";
}

  参数value默认值为“”,该值可以指示对逻辑组件名称的建议,在自动检测的组件的情况下将其转换为Spring bean。

  • @ControllerAdvice

  1. 含义

  @ControllerAdvice是一个@Component,用于定义@ExceptionHandler,@InitBinder和@ModelAttribute方法,适用于所有使用@RequestMapping方法。
  Spring4之前,@ControllerAdvice在同一调度的Servlet中协助所有控制器。Spring4已经改变:@ControllerAdvice支持配置控制器的子集,而默认的行为仍然可以利用。
  在Spring4中, @ControllerAdvice通过annotations(), basePackageClasses(), basePackages()方法定制用于选择控制器子集。

  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerAdvice {
    @AliasFor("basePackages")
    String[] value() default {};

    @AliasFor("value")
    String[] basePackages() default {};

    Class<?>[] basePackageClasses() default {};

    Class<?>[] assignableTypes() default {};

    Class<? extends Annotation>[] annotations() default {};
}

  参数value别名basePackages,默认为空的String字符串数组,表示需要增强的包的路径数组。value和basePackages不能同时指定。
  参数basePackages别名value,默认为空的String字符串数组,表示需要增强的包的路径数组。value和basePackages不能同时指定。
  参数basePackageClasses是类型安全的,用于替换value指定包以选择由@ControllerAdvice 注释类辅助的控制器。
  参数assignableTypes表示应用中需要增强的类的数组。
  参数annotations表示应用中需要增强的注释数组。

  • @ExceptionHandler

  1. 含义

  用于处理特定的类和/或方法中的异常的注释。
  使用此注释的方法允许具有灵活的签名。它们可以按任意顺序具有以下类型的参数:

  • 异常参数:声明为一般异常或更具体的异常。如果注释不通过它的value缩小异常类型,这也可以作为映射提示。
  • 请求和/或响应对象(通常来自Servlet API)。您可以选择任何特定的请求/响应类型,例如 ServletRequest/ HttpServletRequest。
  • 会话对象:通常HttpSession。此类型的参数将强制存在相应的会话。因此,这个参数永远不会null。 请注意,会话访问可能不是线程安全的,特别是在Servlet环境中:如果允许多个请求同时访问会话,请考虑将"synchronizeOnSession"标志切换为“true”。
  • WebRequest或 NativeWebRequest。允许通用请求参数访问以及请求/会话属性访问,而不与本机Servlet API绑定。
  • Locale对于当前请求区域设置(由最可用的区域设置解析程序确定,即LocaleResolver 在Servlet环境中配置)。
  • InputStream/ Reader用于访问请求的内容。这将是Servlet API公开的原始InputStream / Reader。
  • OutputStream/ Writer用于生成响应的内容。这将是Servlet API公开的原始OutputStream / Writer。
  • Model作为从异常处理方法返回模型映射的替代方法。请注意,提供的模型不预先填充常规模型属性,因此始终为空,以便为特定于异常的视图准备模型。

  异常处理方法支持以下返回类型:

  • 一个ModelAndView对象(来自Servlet MVC)。
  • 一个Model对象,通过一个RequestToViewNameTranslator隐式确定视图名称。
  • 一个Map用于暴露一个Model,通过一个RequestToViewNameTranslator隐式确定视图名称。
  • 一个View对象。
  • 一个String值,它被解释为视图名称。
  • 带有@ResponseBody注释的方法(仅限Servlet)来设置响应内容。返回值将使用消息转换器转换为响应流 。
  • 一个HttpEntity或 一个ResponseEntity对象(仅限Servlet)来设置响应头和内容。ResponseEntity正文将被转换并使用消息转换器写入响应流 。
  • 如果方法处理响应本身(通过直接编写响应内容,为此目的声明类型为ServletResponse / HttpServletResponse的参数)或者如果视图名称应该通过RequestToViewNameTranslator隐式确定(未在此处声明响应参数),则返回void处理程序方法签名)。
      在Servlet环境中,您可以将@ExceptionHandler注释与@ResponseStatus 结合使用,以定义HTTP响应的响应状态。
  1. 参数

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {
    Class<? extends Throwable>[] value() default {};
}

  参数value设置注释方法要处理的异常。

  • @ModelAttribute

  1. 含义

  将方法参数或方法返回值绑定到命名模型属性的注释,公开给Web视图。支持带@RequestMapping方法的控制器类。
  可以使用特定的属性名称,通过注释@RequestMapping方法的相应参数,将命令对象公开给Web视图。
  也可以通过使用@RequestMapping方法在控制器类中注释访问器方法,将引用数据公开给Web视图。允许这样的访问器方法具有@RequestMapping方法支持的任何参数, 将模型属性值返回并公开。
  但请注意,当请求处理导致异常时,Web视图无法使用引用数据和所有其他模型内容,因为可能在任何时候引发异常,从而使模型的内容不可靠。因此,@ ExceptionHandler方法不提供对Model参数的访问。

  1. 参数

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ModelAttribute {
    @AliasFor("name")
    String value() default "";

    @AliasFor("value")
    String name() default "";

    boolean binding() default true;
}

  参数value别名name,默认值为“”,指定要绑定的model属性的名称。value和name不能同时指定。
  参数name别名value,默认值为“”,指定要绑定的model属性的名称。value和name不能同时指定。
  参数binding设置是否允许直接在@ModelAttribute方法参数或从@ModelAttribute方法返回的属性上声明数据绑定,这两种方法都会阻止该属性的数据绑定。

  • @InitBinder

  1. 含义

  用于标识初始化WebDataBinder的方法,该方法将用于填充带注释的方法的命令和表单对象参数。
  这样的init-binder方法支持RequestMapping支持的所有参数,命令/表单对象和相应的验证结果对象除外。 Init-binder方法不能有返回值;它们通常被宣布为无效。
  典型的参数是WebDataBinder与WebRequest或Locale的组合,允许注册特定于上下文的编辑器。

  1. 参数

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface InitBinder {
    String[] value() default {};
}

  参数value设置此init-binder方法应用于的命令/表单属性和/或请求参数的名称。

  • @WebAppConfiguration

  1. 含义

  @WebAppConfiguration是一个类级别注释,用于声明为集成测试加载的ApplicationContext应该是WebApplicationContext。
  测试类上存在@WebAppConfiguration指示应使用Web应用程序根路径的默认值为测试加载WebApplicationContext。要覆盖默认值,请通过value()属性指定显式资源路径。
  请注意,@WebAppConfiguration必须与@ContextConfiguration结合使用,可以在单个测试类中,也可以在测试类层次结构中使用。

  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface WebAppConfiguration {
    String value() default "src/main/webapp";
}

  参数value指定Web应用程序根目录的资源路径。

  • @EnableAutoConfiguration

  1. 含义

  此注释自动载入应用程序所需的所有Bean——这依赖于Spring Boot在类路径中的查找。该注解组合了@Import注解,@Import注解导入了EnableAutoCofigurationImportSelector类,它使用SpringFactoriesLoader.loaderFactoryNames方法来扫描具有META-INF/spring.factories文件的jar包。而spring.factories里声明了有哪些自动配置。

  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({EnableAutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

    Class<?>[] exclude() default {};

    String[] excludeName() default {};
}

  参数exclude指定的Configuration类不会生成bean并且不会被使用。
  参数excludeName指定的Configuration类的全路径名称,作用同上。

  • @SpingBootApplication

  1. 含义

  SpringBoot的核心注解,主要目的是开启自动配置。它也是一个组合注解,主要组合了@Configurer,@EnableAutoConfiguration(核心)和@ComponentScan。可以通过@SpringBootApplication(exclude={想要关闭的自动配置的类名.class})来关闭特定的自动配置。

  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
    @AliasFor(
        annotation = EnableAutoConfiguration.class,
        attribute = "exclude"
    )
    Class<?>[] exclude() default {};

    @AliasFor(
        annotation = EnableAutoConfiguration.class,
        attribute = "excludeName"
    )
    String[] excludeName() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackages"
    )
    String[] scanBasePackages() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackageClasses"
    )
    Class<?>[] scanBasePackageClasses() default {};
}

  参数exclude同EnableAutoConfiguration.exclude()。
  参数excludeName同EnableAutoConfiguration.exclude()。
  参数scanBasePackages同ComponentScan.basePackages()。
  参数scanBasePackageClasses同ComponentScan.basePackageClasses()。

  • @ImportResource

  1. 含义

  指示包含要导入的bean定义的一个或多个资源。
  与@Import一样,此批注提供的功能类似于Spring XML中的元素。它通常在将@Configuration类设计为由AnnotationConfigApplicationContext引导时使用,但仍需要某些XML功能(如命名空间)。
  默认情况下,如果以“.groovy”结尾,将使用GroovyBeanDefinitionReader处理value()属性的参数;否则,将使用XmlBeanDefinitionReader来解析Spring XML文件。可选地,可以声明reader()属性,允许用户选择自定义BeanDefinitionReader实现。

  1. 参数

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
public @interface ImportResource {
    @AliasFor("locations")
    String[] value() default {};

    @AliasFor("value")
    String[] locations() default {};

    Class<? extends BeanDefinitionReader> reader() default BeanDefinitionReader.class;
}

  参数value别名locations,默认值为空字符串数组。指定要导入的资源位置。
  参数locations别名value,默认值为空字符串数组。指定要导入的资源位置。
  参数reader指定自定义的BeanDefinitionReader接口实现类来处理通过value()属性指定的资源。

  • @ConfigurationProperties

  1. 含义

  将properties属性与一个Bean及其属性相关联,从而实现类型安全的配置。

  1. 参数

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ConfigurationProperties {
    @AliasFor("prefix")
    String value() default "";

    @AliasFor("value")
    String prefix() default "";

    boolean ignoreInvalidFields() default false;

    boolean ignoreNestedProperties() default false;

    boolean ignoreUnknownFields() default true;

    /** @deprecated */
    @Deprecated
    boolean exceptionIfInvalid() default true;
}

  参数value别名prefix,默认参数为“”,用于指定配置文件中的前缀。假设配置文件内容如下:

connection.username=admin
connection.password=password
connection.remoteAddress=192.168.1.1

  这时候我们可以定义一个实体类在装载配置文件信息

@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {

    private String username;
    private String remoteAddress;
    private String password ;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getRemoteAddress() {
        return remoteAddress;
    }
    public void setRemoteAddress(String remoteAddress) {
        this.remoteAddress = remoteAddress;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

}

  配置文件中的数据就会自动封装到bean中。
  参数prefix别名value,效果同value。
  参数ignoreInvalidFields设置当数据类型不匹配时是否忽略。
  参数ignoreNestedProperties设置是否忽略嵌套属性。
  参数ignoreUnknownFields设置是否忽略未知的配置属性。
  参数exceptionIfInvalid效果同ignoreInvalidFields,已过时。

  • @ConditionalOnBean

  1. 含义

  条件注解。当容器里有指定Bean的条件下执行方法。

  1. 参数

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({OnBeanCondition.class})
public @interface ConditionalOnBean {
    Class<?>[] value() default {};

    String[] type() default {};

    Class<? extends Annotation>[] annotation() default {};

    String[] name() default {};

    SearchStrategy search() default SearchStrategy.ALL;

    Class<?>[] parameterizedContainer() default {};
}

  参数value指定依赖的bean的class类数组。
  参数type指定依赖的bean的全路径名称字符串数组。
  参数annotation指定依赖的bean带有的注释类名。
  参数name指定依赖的bean的名称。
  参数search决定是否应考虑应用程序上下文层次结构(父上下文)的策略。
  参数parameterizedContainer指定可能在其泛型参数中包含指定bean类型的其他类。

  • @ConditionalOnClass

  1. 含义

  条件注解。当类路径下有指定的类的条件下执行方法。

  1. 参数

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
> @Documented
@Conditional({OnClassCondition.class})
public @interface ConditionalOnClass {
    Class<?>[] value() default {};

    String[] name() default {};
}

  参数value指定必须存在的类。
  参数name指定必须存在的类名。

  • @ConditionalOnExpression

  1. 含义

  条件注解。基于SpEL表达式作为判断条件。

  1. 参数

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Conditional({OnExpressionCondition.class})
public @interface ConditionalOnExpression {
    String value() default "true";
}

  参数value设置用于判断的SpEL表达式。

  • @ConditionalOnJava

  1. 含义

  条件注解。基于JVM版本作为判断条件。

  1. 参数

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({OnJavaCondition.class})
public @interface ConditionalOnJava {
    ConditionalOnJava.Range range() default ConditionalOnJava.Range.EQUAL_OR_NEWER;

    ConditionalOnJava.JavaVersion value();

    public static enum JavaVersion {
        NINE(9, "1.9", "java.security.cert.URICertStoreParameters"),
        EIGHT(8, "1.8", "java.util.function.Function"),
        SEVEN(7, "1.7", "java.nio.file.Files"),
        SIX(6, "1.6", "java.util.ServiceLoader");

        private final int value;
        private final String name;
        private final boolean available;

        private JavaVersion(int value, String name, String className) {
            this.value = value;
            this.name = name;
            this.available = ClassUtils.isPresent(className, this.getClass().getClassLoader());
        }

        public boolean isWithin(ConditionalOnJava.Range range, ConditionalOnJava.JavaVersion version) {
            Assert.notNull(range, "Range must not be null");
            Assert.notNull(version, "Version must not be null");
            switch(range) {
            case EQUAL_OR_NEWER:
                return this.value >= version.value;
            case OLDER_THAN:
                return this.value < version.value;
            default:
                throw new IllegalStateException("Unknown range " + range);
            }
        }

        public String toString() {
            return this.name;
        }

        public static ConditionalOnJava.JavaVersion getJavaVersion() {
            ConditionalOnJava.JavaVersion[] var0 = values();
            int var1 = var0.length;

            for(int var2 = 0; var2 < var1; ++var2) {
                ConditionalOnJava.JavaVersion candidate = var0[var2];
                if (candidate.available) {
                    return candidate;
                }
            }

            return SIX;
        }
    }

    public static enum Range {
        EQUAL_OR_NEWER,
        OLDER_THAN;

        private Range() {
        }
    }
}

  参数range配置value()中配置的值是否应被视为上限或更低的包含边界。
  参数value指定要检查的JavaVersion。

  • @ConditionalOnJndi

  1. 含义

  条件注解。在JNDI存在的条件下查找指定的位置。

  1. 参数

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({OnJndiCondition.class})
public @interface ConditionalOnJndi {
    String[] value() default {};
}

  参数value指定JNDI位置,其中一个必须存在。

  • @ConditionalOnMissingBean

  1. 含义

  条件注解。当容器里没有指定Bean的情况下执行方法。

  1. 参数

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({OnBeanCondition.class})
public @interface ConditionalOnMissingBean {
    Class<?>[] value() default {};

    String[] type() default {};

    Class<?>[] ignored() default {};

    String[] ignoredType() default {};

    Class<? extends Annotation>[] annotation() default {};

    String[] name() default {};

    SearchStrategy search() default SearchStrategy.ALL;

    Class<?>[] parameterizedContainer() default {};
}

  参数value指定应检查的bean的class类型。
  参数type指定应检查的bean的class全路径名称。
  参数ignored表示匹配bean时应忽略的bean的class类型。
  参数ignoredType表示匹配bean时应忽略的bean的class全路径名称。
  参数annotation指定应该检查的bean的注释类型。
  参数name表示要检查的bean的名称。
  参数search决定是否应考虑应用程序上下文层次结构(父上下文)的策略。
  参数parameterizedContainer指定可能在其泛型参数中包含指定bean类型的其他类。

  • @ConditionalOnMissingClass

  1. 含义

  条件注解。当类路径下没有指定的类的情况下执行方法。

  1. 参数

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({OnClassCondition.class})
public @interface ConditionalOnMissingClass {
    String[] value() default {};
}

  参数value表示不存在的类的名称。

  • @ConditionalOnNotWebApplication

  1. 含义

  条件注解。当前项目不是web项目的条件下执行方法。

  1. 参数

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({OnWebApplicationCondition.class})
public @interface ConditionalOnNotWebApplication {
}

  无参数。

  • @ConditionalOnResource

  1. 含义

  条件注解。类路径有指定的资源时执行方法。

  1. 参数

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({OnResourceCondition.class})
public @interface ConditionalOnResource {
    String[] resources() default {};
}

  参数resources表示必须存在的资源路径。

  • @ConditionalOnSingleCandidate

  1. 含义

  条件注解。当指定Bean在容器中只有一个,有多个的情况其可以指定首选的Bean。

  1. 参数

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({OnBeanCondition.class})
public @interface ConditionalOnSingleCandidate {
    Class<?> value() default Object.class;

    String type() default "";

    SearchStrategy search() default SearchStrategy.ALL;
}

  参数value指定应检查的bean的class类型。
  参数type指定应检查的bean的class全路径名称。
  参数search决定是否应考虑应用程序上下文层次结构(父上下文)的策略。

  • @ConditionalOnWebApplication

  1. 含义

  条件注解。当前项目是web项目的情况下执行方法。

  1. 参数

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({OnWebApplicationCondition.class})
public @interface ConditionalOnWebApplication {
}

  无参数。

  • @EnableConfigurationProperties

  1. 含义

  启用对ConfigurationProperties带注释的bean的支持。ConfigurationProperties bean可以以标准方式注入(例如使用@Bean方法),或者为方便起见,可以直接在此注释上指定。

  1. 参数

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({EnableConfigurationPropertiesImportSelector.class})
public @interface EnableConfigurationProperties {
    Class<?>[] value() default {};
}

  参数value表示使用Spring快速注入ConfigurationProperties注释bean。

  • @AutoConfigureAfter

  1. 含义

  在指定的自动配置类之后再配置。

  1. 参数

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface AutoConfigureAfter {
    Class<?>[] value() default {};

    String[] name() default {};
}

  参数value指定在此配置执行之前应该已应用的自动配置类。
  参数name指定在此配置执行之前应该已应用的自动配置类的全路径名称。

  • @Constraint

  1. 含义

  将注释标记为Bean Validation约束。
  给定的约束注释必须被@Constraint注释,该注释引用其约束验证实现的列表。
  被@Constraint标记的注释必须包含以下属性:

  1. String message() default [...];应该默认为由约束的完全限定类名后跟的错误消息键 .message。例如"{com.acme.constraints.NotSafe.message}"。
  2. Class<?>[] groups() default {}; 供用户自定义目标组。
  3. Class<? extends Payload>[] payload() default {}; 出于可扩展性的目的。

  构建通用和交叉参数的约束时,约束注释必须承载validationAppliesTo()属性。如果约束是以注释元素为目标,则约束是通用的,如果它以方法或构造函数的参数数组为目标,则是交叉参数。   

ConstraintTarget validationAppliesTo() default ConstraintTarget.IMPLICIT;  

  此属性允许约束用户选择约束是否以可执行文件的返回类型或其参数数组为目标。   如果两种ConstraintValidator附加到约束,一个目标是ValidationTarget.ANNOTATED_ELEMENT,另一个目标是ValidationTarget.PARAMETERS, 或者如果ConstraintValidator同时针对ANNOTATED_ELEMENT和PARAMETERS。那么这个约束既是通用的,也是参数交叉的。
  

  1. 参数

@Documented
@Target({ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Constraint {
    Class<? extends ConstraintValidator<?, ?>>[] validatedBy();
}

  参数validatedBy指定一个或多个实现了ConstraintValidator接口的类来进行数据校验。

参考文献: