006-spring Boot Auto Configuration

Source: Internet
Author: User

First, interface condition, Conditional (principle)

Mainly provide methods

Boolean matches (conditioncontext context, annotatedtypemetadata metadata);

True: Indicates assembly

False: Indicates no assembly

Note: the Conditional () parameter is an array, and the array is true before assembling

@Target ({elementtype.type, elementtype.method}) @Retention (retentionpolicy.runtime) @Documented  public @Interface  Conditional {    /**     * All {@link  Condition}s that must {@linkplain  condition#matches Match} * On order for the component to be     re gistered.      */     Classextends condition>[] Value ();
View Code

Usually used in conjunction with.

Example:

Interface: Encodingconvert

 Package Com.lhx.spring.springboot_auto_config;  Public Interface Encodingconvert {}
View Code

Interface implementation one: Utf8encodingconvert

 Package Com.lhx.spring.springboot_auto_config;  Public class Implements Encodingconvert {}
View Code

Interface implementation two: Gbkencodingconvert

 Package Com.lhx.spring.springboot_auto_config;  Public class Implements Encodingconvert {}
View Code

Configuration class:

 PackageCom.lhx.spring.springboot_auto_config;Importorg.springframework.boot.SpringBootConfiguration;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Conditional; @SpringBootConfiguration Public classencodingconvertconfiguration {@Bean PublicEncodingconvert Creategbkencodingconvert () {return NewGbkencodingconvert (); } @Bean PublicEncodingconvert Createutf8encodingconvert () {return NewUtf8encodingconvert (); }}
View Code

APP:

 PackageCom.lhx.spring.springboot_auto_config;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;ImportOrg.springframework.context.ConfigurableApplicationContext;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Condition;Importorg.springframework.context.annotation.Conditional; @SpringBootApplication Public classApp {@Bean PublicRunnable createrunnable () {return(){System.out.println ("Spring Boot is running");    }; }     Public Static voidMain (string[] args) {Configurableapplicationcontext context= Springapplication.run (App.class, args); Context.getbean (Runnable.class). Run (); //You can modify the-DFILE.ENCODING=GBK with the start parameterSystem.out.println (System.getproperty ("file.encoding")); System.out.println (Context.getbeansoftype (Encodingconvert.class));    Context.close (); }}
View Code

At this point, you will find that even an interface implementation will be assembled.

Utf8condition Implementing the Condition interface

 PackageCom.lhx.spring.springboot_auto_config;Importorg.springframework.context.annotation.Condition;ImportOrg.springframework.context.annotation.ConditionContext;ImportOrg.springframework.core.type.AnnotatedTypeMetadata; Public classUtf8conditionImplementsCondition {@Override Public Booleanmatches (conditioncontext context, Annotatedtypemetadata metadata) {String encoding= System.getproperty ("file.encoding"); if(Encoding! =NULL) {            return"Utf-8". Equalsignorecase (encoding); }        return false; }}
View Code

Gbkcondition Implementing the Condition interface

 PackageCom.lhx.spring.springboot_auto_config;Importorg.springframework.context.annotation.Condition;ImportOrg.springframework.context.annotation.ConditionContext;ImportOrg.springframework.core.type.AnnotatedTypeMetadata; Public classGbkconditionImplementsCondition {@Override Public Booleanmatches (conditioncontext context, Annotatedtypemetadata metadata) {String encoding= System.getproperty ("file.encoding"); if(Encoding! =NULL) {            return"GBK". Equalsignorecase (encoding); }        return false; }}
View Code

Modifying the Configuration Class

 PackageCom.lhx.spring.springboot_auto_config;Importorg.springframework.boot.SpringBootConfiguration;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Conditional; @SpringBootConfiguration Public classencodingconvertconfiguration {@Bean @Conditional (gbkcondition.class)     PublicEncodingconvert Creategbkencodingconvert () {return NewGbkencodingconvert (); } @Bean @Conditional (utf8condition.class)     PublicEncodingconvert Createutf8encodingconvert () {return NewUtf8encodingconvert (); }}
View Code

At this point, you will find that the interface class is assembled according to the file.encoding value.

Can be increased at startup parameters

-dfile.encoding=gbk

  

Then debug and find the Assembly class has changed.

Note: @Conditional can also function on a class

Second, Spring provides the conditional automatic configuration

Jar:spring-boot-autoconfigure, org.springframework.boot.autoconfigure.condition; that is, Spring-boot provides

Conditionalonbean: Assembled when a bean is present

Conditionalonmissingbean: Assembly When a bean is not present

Conditionalonclass: When Classpath is assembled

Conditionalonexpression:

CONDITIONALONJAVA:JDK version meets time to assemble

Conditionalonnotwebapplication: Not a Web environment to assemble
Conditionalonwebapplication: It's a web environment to assemble

Conditionalonresource: The resource exists before assembling

Conditionalonproperty: Configuration exists before Assembly

Example one: Conditionalonproperty configuration is configured when there is a match

Add Configuration Class

 PackageCom.lhx.spring.springboot_auto_config;Importorg.springframework.boot.SpringBootConfiguration;ImportOrg.springframework.boot.autoconfigure.condition.ConditionalOnProperty;ImportOrg.springframework.context.annotation.Bean; @SpringBootConfiguration Public classuserconfiguration {@Bean @ConditionalOnProperty (name= "Runnable.enable", Havingvalue = "true")     PublicRunnable createrunnable () {return() {        }; }}
View Code

APP2 Writing

 PackageCom.lhx.spring.springboot_auto_config;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;ImportOrg.springframework.context.ConfigurableApplicationContext;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Condition;Importorg.springframework.context.annotation.Conditional; @SpringBootApplication Public classAPP2 { Public Static voidMain (string[] args) {Configurableapplicationcontext context= Springapplication.run (App2.class, args); System.out.println (Context.getbeansoftype (Runnable.class));    Context.close (); }}
View Code

The default is no assembly.

Can be assembled by adding runnable.enable=true in Application.properties

or @conditionalonproperty (name = "Runnable.enable", Havingvalue = "true") increase

Matchifmissing=true, indicating that the configuration does not take effect when

Example two: Conditionalonclass Classpath has a class to assemble

Add or remove Maven to see the effect

        <Dependency>            <groupId>Com.google.code.gson</groupId>            <Artifactid>Gson</Artifactid>            <version>2.8.2</version>        </Dependency>

Using code

    @Bean    @ConditionalOnClass (name= "Com.google.gson.Gson")    public  Runnable creategsonrunnable () {        return () {        };    }

Example three, Conditionalonbean: assembly based on whether a bean exists in the container

    @Bean    @ConditionalOnBean (name= "User")    public  Runnable Createonbeanrunnable () {        return () {        };    }

006-spring Boot Auto Configuration

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.