一、条件注解@Conditional,组合注解,元注解

1.

@Conditional:满足特定条件创建一个Bean,SpringBoot就是利用这个特性进行自动配置的。

例子:

首先,两个Condition,判断当前系统是否是Windows或者Linux(True False)

然后,2个ListService实现类,表明不同系统下的ListService实现。

主要,ConditionConfig使用了Java配置与@Conditional注解,根据LinuxCondition,或者WindowsCondition作为判断条件

产生相应与系统匹配的实现类。

最后,App.java 测试成功。

package com.springboot.springboot_test2_1;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata; public class LinuxCondition implements Condition { @Override
public boolean matches(ConditionContext arg0, AnnotatedTypeMetadata arg1) {
return arg0.getEnvironment().getProperty("os.name").contains("Linux");
} }

LinuxCondition.java

package com.springboot.springboot_test2_1;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata; public class WindowsCondition implements Condition { @Override
public boolean matches(ConditionContext arg0, AnnotatedTypeMetadata arg1) {
return arg0.getEnvironment().getProperty("os.name").contains("Windows");
} }

WindowsCondition.java

package com.springboot.springboot_test2_1;

public interface ListService {
public String showListCmd();
}

ListService.java

package com.springboot.springboot_test2_1;

public class LinuxListService implements ListService{

    @Override
public String showListCmd() {
return "ls";
} }

LinuxListService.java

package com.springboot.springboot_test2_1;

public class WindowsListService implements ListService{

    @Override
public String showListCmd() {
return "dir";
} }

WindowsListService.java

package com.springboot.springboot_test2_1;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration; @Configuration
public class ConditionConfig { @Bean
@Conditional(WindowsCondition.class)
public ListService windowsListService() {
return new WindowsListService();
} @Bean
@Conditional(LinuxCondition.class)
public ListService linuxListService() {
return new LinuxListService();
} }

ConditionConfig.java

package com.springboot.springboot_test2_1;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; /**
* Hello world!
*
*/
public class App {
public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(
ConditionConfig.class); ListService ls = context.getBean(ListService.class);
System.out.println(context.getEnvironment().getProperty("os.name")
+ "系统下的列表命令为:" + ls.showListCmd());
}
}

App.java

2.

元注解:可以注解到别的注解上的注解。

组合注解:元注解+被注解=组合注解。

例子:

package com.springboot.springboot_test2_1;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@ComponentScan
public @interface testConfig {
String[] value() default{};
}

testConfig.java

二、通过条件注解@Conditional,组合注解,元注解理解SpringBoot的自动配置

@SpringBootApplication,源码:

@Target({java.lang.annotation.ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters={@org.springframework.context.annotation.ComponentScan.Filter(type=org.springframework.context.annotation.FilterType.CUSTOM, classes={org.springframework.boot.context.TypeExcludeFilter.class}), @org.springframework.context.annotation.ComponentScan.Filter(type=org.springframework.context.annotation.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 {};
}

SpringBootApplication源码

它的核心功能是由@EnableAutoConfiguration注解提供的,

@EnableAutoConfiguration,源码:

@SuppressWarnings("deprecation")
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration { String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; /**
* Exclude specific auto-configuration classes such that they will never be applied.
* @return the classes to exclude
*/
Class<?>[] exclude() default {}; /**
* Exclude specific auto-configuration class names such that they will never be
* applied.
* @return the class names to exclude
* @since 1.3.0
*/
String[] excludeName() default {}; }

EnableAutoConfiguration源码

@EnableAutoConfiguration其中的@AutoConfigurationPackage,会扫描/META-INF/spring.factories文件中的jar包,

spring.factories文件如下:

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\

……

2、核心注解

spring.factories文件里每一个xxxAutoConfiguration文件一般都会有下面的条件注解:

@ConditionalOnBean:当容器里有指定Bean的条件下

@ConditionalOnClass:当类路径下有指定类的条件下

@ConditionalOnExpression:基于SpEL表达式作为判断条件

@ConditionalOnJava:基于JV版本作为判断条件

@ConditionalOnJndi:在JNDI存在的条件下差在指定的位置

@ConditionalOnMissingBean:当容器里没有指定Bean的情况下

@ConditionalOnMissingClass:当类路径下没有指定类的条件下

@ConditionalOnNotWebApplication:当前项目不是Web项目的条件下

@ConditionalOnProperty:指定的属性是否有指定的值

@ConditionalOnResource:类路径是否有指定的值

@ConditionalOnSingleCandidate:当指定Bean在容器中只有一个,或者虽然有多个但是指定首选Bean

@ConditionalOnWebApplication:当前项目是Web项目的条件下。

上面@ConditionalOnXXX都是组合@Conditional元注解,使用了不同的条件Condition

[读书笔记] 二、条件注解@Conditional,组合注解,元注解的更多相关文章

  1. Java开发笔记(八十二)注解的基本单元——元注解

    Java的注解非但是一种标记,还是一种特殊的类型,并且拥有专门的类型定义.前面介绍的五种内置注解,都可以找到对应的类型定义代码,例如查看注解@Override的源码,发现它的代码定义是下面这样的: @ ...

  2. spring揭秘 读书笔记 二 BeanFactory的对象注册与依赖绑定

    本文是王福强所著<<spring揭秘>>一书的读书笔记 我们前面就说过,Spring的IoC容器时一个IoC Service Provider,而且IoC Service Pr ...

  3. spring揭秘 读书笔记 二 BeanFactory的对象注冊与依赖绑定

    本文是王福强所著<<spring揭秘>>一书的读书笔记 我们前面就说过,Spring的IoC容器时一个IoC Service Provider,并且IoC Service Pr ...

  4. ES6读书笔记(二)

    前言 前段时间整理了ES6的读书笔记:<ES6读书笔记(一)>,现在为第二篇,本篇内容包括: 一.数组扩展 二.对象扩展 三.函数扩展 四.Set和Map数据结构 五.Reflect 本文 ...

  5. 《你必须知道的.NET》读书笔记二:小OO有大原则

    此篇已收录至<你必须知道的.Net>读书笔记目录贴,点击访问该目录可以获取更多内容. 一.单一职责原则 (1)核心思想:一个类最好只做一件事,只有一个引起它变化的原因 (2)常用模式:Fa ...

  6. Mastering Web Application Development with AngularJS 读书笔记(二)

    第一章笔记 (二) 一.scopes的层级和事件系统(the eventing system) 在层级中管理的scopes可以被用做事件总线.AngularJS 允许我们去传播已经命名的事件用一种有效 ...

  7. 【记】《.net之美》之读书笔记(二) C#中的泛型

    前言 上一篇读书笔记,很多小伙伴说这本书很不错,所以趁着国庆假期,继续我的读书之旅,来跟随书中作者一起温习并掌握第二章的内容吧. 一.理解泛型 1.为什么要使用泛型?-----通过使用泛型,可以极大地 ...

  8. how tomcat works 读书笔记(二)----------一个简单的servlet容器

    app1 (建议读者在看本章之前,先看how tomcat works 读书笔记(一)----------一个简单的web服务器 http://blog.csdn.net/dlf123321/arti ...

  9. java读书笔记二

    这是我的一些读书笔记: 我研究了一下面向对象: 面向对象符合人类看待事物的一般规律,对象的方法的实现细节是包装的,只有对象方法的实现者了解细节 我觉得面向过程是由过程.步骤.函数组成,过程是核心,面向 ...

随机推荐

  1. a.变量及基本数据结构

    1. Scala 中有两种类型的变量:可变变量和不可变变量 ,可变变量使用关键字var定义,不可变变量用val定义 : 2.Scala 中变量定义的时候必须初始化赋值,可以使用占位符(_)来初始化,基 ...

  2. Nginx文档-初学者指南

    原文档: http://nginx.org/en/docs/beginners_guide.html 译者:Oopsguy 本指南旨在介绍nginx基本内容和一些在Nginx上可以完成的简单任务.这里 ...

  3. Eclipse Jetty插件安装

    Eclipse Jetty插件安装 使用方法一: 本地资源包插件下载地址:http://pan.baidu.com/s/1sjNP5Id 或者是地址:http://pan.baidu.com/s/1b ...

  4. cxf的使用以及与SSH的整合

    经历过一小段忙碌的时间,终于有时间开始整理项目中曾遇到的技术难点,并不是什么新颖的技术难点,只是自己在这样方面所了解的不健全或者是没有了解透彻,现在都抽时间进行整理. 首先就是需要在ssh的系统中整合 ...

  5. hdu--1798--Doing Homework again(贪心)

    Doing Homework again Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Oth ...

  6. bower基本使用

    bower是什么? bower是基于nodejs的静态资源管理工具,由twitter公司开发.维护,使用它可以方便的安装.更新.卸载前端类库,同时解决类库之前的依赖关系. 依赖环境 bower依赖于n ...

  7. MySQL开发指南

    数据库开发是数据库管理系统(DBMS)和数据库应用软件设计研发的总称,数据运维.参与数据库生产环境的问题优化和解决等方面的事宜. 1.关于MySQL数据库 2.搭建MySQL环境 3.入门常用SQL. ...

  8. 【HTTP权威指南】第1 章 HTTP 概述

    1.1 HTTP--因特网的多媒体信使 ................................................................................ ...

  9. 脱壳练习之bitarts 5.0

    运行界面 一开始不是PUSHAD,这里我们跟到PUSHAD指令处,按F7执行该指令,接着在寄存器窗口中定位到ESP寄存器的值,在其上面单击鼠标右键选择-Follow in Dump. 仅允许非商业转载 ...

  10. 一步一步学多线程-ThreadLocal源码解析

    上网查看了很多篇ThreadLocal的原理的博客,上来都是文字一大堆,费劲看了半天,大脑中也没有一个模型,想着要是能够有一张图明确表示出来ThreadLocal的设计该多好,所以就自己看了源码,画了 ...