Spring Boot Series VI: Automatic configuration of @Conditional and spring boot

Source: Internet
Author: User

We know that the Spring boot Autoconfiguration feature can determine which of the spring configurations should be used depending on the circumstances, not which one should be used, for example:

    • Is spring's jdbctemplate in classpath? If it is, and DataSource is present, a JdbcTemplate bean is automatically configured
    • Is thymeleaf in classpath? If yes, automatically configures the Thymeleaf template parser, view resolver, template engine

How does that one come true? The reason for this is that it takes advantage of spring's conditional configuration, which allows the configuration to exist in the app, but ignores these configurations until certain conditions are met.

To implement the conditional configuration we need to use the @conditional conditional annotation. Then write a small example to feel how the @conditional works.

One, @Conditional small example

We know that the command to display the list under Windows is dir, and the command to display the list under Linux is LS, and based on the conditional configuration, we can implement different values to be returned under different operating systems.

  1. Definition of condition of judgment
    1. ) decision condition under Windows
       /**   * implement Spring Condition interface, and override the matches () method if the operating system is Windows returns True *  */ public  class  windowscondition   condition{@Override  public< /span> boolean   matches (Conditioncontext Context, Annotatedtypemetadata metadata) { return  Context.geten    Vironment (). GetProperty ("Os.name"). Contains ("Windows" 
    2. ) The criteria under Linux
      /***/Publicclassimplements  condition{    @Override     Publicboolean  matches (conditioncontext context, annotatedtypemetadata metadata) {                 return context.getenvironment (). GetProperty ("Os.name"). Contains ("Linux");    }    }
  2. The class of beans under different systems
    1. ) interface
       Public Interface Listservice {    public  String showlistline ();}
    2. ) The Bean class under Windows
       Public class Implements listservice{    @Override    public  String showlistline () {        return "dir";    }}
    3. ) The class of the Bean under Linux
       Public class Implements listservice{    @Override    public  String showlistline () {        return ' ls ' ;    }}
  3. Configuration class
    @Configuration Public classConditionconfig {/*** Return Windowslistservice instances with @conditional annotations, which meet windows criteria **/@Bean @Conditional (windowscondition.class)     PublicListservice Windonwslistservice () {return NewWindowslistservice (); }    /*** Return to Linuxlistservice instances with @conditional annotations and Linux conditions **/@Bean @Conditional (linuxcondition.class)     PublicListservice Linuxlistservice () {return NewLinuxlistservice (); }}
  4. Test class
     public  class   Conditiontest { public  static  Span style= "color: #0000ff;" >void   main (string[] args) {Annotationconfigapplicationcontext context  = new  annotationconfigapplicationcontext (conditionconfig.class  ); Listservice Listservice  = Context.getbean (Listservice.        Class  ); System.out. println (Context.getenvironment (). GetProperty ( "os.name") + "List command under System:" + Listservice.showlistline ()); }}
  5. Run the test class, because my is the windows7 system, so the result is
    The list commands under Windows 7 system are: Dir

    If you are a Linux system, the result will be

    The list command under the Linux system is: LS

Second, the conditional configuration of spring boot

There will be a jar package named Spring-boot-autoconfigure in the Spring boot project

The conditional configuration is implemented in this jar, which uses the following conditional annotations, which begin with @conditional:

Next we look at a source of the following:

Take Jdbctemplateautoconfiguration as an example, it contains this code:

@Bean    @Primary    @ConditionalOnMissingBean (jdbcoperations. class )    public  jdbctemplate jdbctemplate () {        returnnew JdbcTemplate (this. dataSource);    }

A jdbctemplate bean is initialized only if there is no jdbcoperations (if you look at the source code of the JdbcTemplate, you will find that the JdbcTemplate class implements the JdbcOperations interface) instance.

Based on the above content, we can read the automatic configuration of the relevant source code.

Spring Boot Series VI: Automatic configuration of @Conditional and spring boot

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.