Spring Boot automatic configuration (auto-configuration), @EnableAutoConfiguration, spring beans and Dependency injection __spring-boot

Source: Internet
Author: User
Tags naming convention

automatic configuration (auto-configuration)

Automatic configuration (auto-configuration) is one of the most important features of spring boot, because the feature is based on the classpath of the application (this is mainly based on Maven Pom.xml decision), annotations and some other Java configuration descriptors automatically configure the spring boot application. For example, if you configure H2 in your classpath (add H2 dependencies to pom.xml files), you do not have to maintain any data connections, and Spring boot automatically configures a memory database.

Auto-configuration is non-intrusive, you can start defining your own configuration at any time to replace a particular part of the auto-configuration. For example, if you add your own datasource bean, the default embedded database support will be invalidated.

If you find certain automatic configuration classes that you do not want to apply, you can disable them by using the exclusion properties of @EnableAutoConfiguration annotations.

Import org.springframework.boot.autoconfigure.*;
Import org.springframework.boot.autoconfigure.jdbc.*;
Import org.springframework.context.annotation.*;
@Configuration
@EnableAutoConfiguration (Exclude={datasourceautoconfiguration.class}) public
class myconfiguration {
}

If the class is not in Classpath, you can also use the Excludename attribute of the annotation and specify the fully qualified name of the class (fully qualified name) to exclude. You can also use the Spring.autoconfigure.exclude property to control the list of automatically configured classes.

@EnableAutoConfiguration and @enable<technology> annotations
@enable<technology> annotations are provided in the spring framework and some of its modules, such as Spring Core, Spring data,spring AMQP, spring integration. As @enabletransactionmanagement, @EnableRabbit, @EnableIntegration is part of the module mentioned in the appeal. In the spring application, you can use them according to the "Conventions larger than configuration (Convention over configuration)" pattern, which makes your application very easy to develop without worrying about maintenance because of too many profiles.

Spring Boot takes advantage of these annotations, which are used in @enableautoconfiguration annotations to perform automatic configuration (auto-configuration). Let's take a closer look at the @enableautoconfiguration annotation and take a look at the logic behind it.

@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 {};
}

We know that this class will try to guess and configure the bean that is needed in the application. The Auto-configuration class is based on the configuration of the Classpath (Pom.xml configuration) and is defined in the application beans is used, but the magic is played by Org.springframework.boot.autoconfigure.EnableAuto Configurationimportselector class, which can find all of the required configuration classes.

The Enableautoconfigurationimportselector class inherits from the Autoconfigurationimportselector class (different versions of spring boot may be different), and the class has many methods, But one of the most important ways to make automatic configuration (auto-configuration) effective is the Getcandidateconfiguration method.

//...
Protected list<string> getcandidateconfigurations (annotationmetadata metadata,
            annotationattributes attributes) {
    list<string> configurations = Springfactoriesloader.loadfactorynames (
                Getspringfactoriesloaderfactoryclass (), Getbeanclassloader ());
        Assert.notempty (configurations,
                "No Auto Configuration classes found in Meta-inf/spring.factories.") If you
                        are "+" are using a custom packaging, make sure that file is correct. ")
    ; return configurations;
}
//...

The

Getcandidateconfigurations method returns springfactoriesloader.loadfactorynames,springfactoriesloader.loadfactories to find Spring-boot -autoconfigure the meta-inf/spring.factories file defined in the jar.

# initializers Org.springframework.context.applicationcontextinitializer=\ Org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer. # application
Listeners org.springframework.context.applicationlistener=\
Org.springframework.boot.autoconfigure.BackgroundPreinitializer # 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.messagesourceautoconfiguration,\
Org.springframework.boot.autoconfigure.propertyplaceholderautoconfiguration,\
Org.springframework.boot.autoconfigure.batch.batchautoconfiguration,\
Org.springframework.boot.autoconfigure.cache.cacheautoconfiguration,\ Org.springframework.boot.autoconfigure.cassandra.cassandraautoconfiguration,\ Org.springframeworK.boot.autoconfigure.cloud.cloudautoconfiguration,\ ..... 

As you can see, in the Spring.factories file, you define all the classes that may be configured automatically at application run time.

Building Code

Spring boot does not require any special code structure, however, here are some useful best practices.

Using the default package: When a class does not contain a package declaration, it is considered to be under default package and is generally not recommended and avoids the use of default package. Because classes from each jar will be read for spring boot applications that use @ComponentScan, @EntityScan, or @SpringBootApplication annotations, this can create some special problems.

Locate the main application class: It is recommended that you place the main application class in the root package (root package) above the other classes. You usually use @EnableAutoConfiguration to annotate your main class and secretly define a basic "search package" for some items. For example, if you are writing a JPA application, all @entity annotation entries in the package of the class that are annotated by @EnableAutoConfiguration will be retrieved.

Using the root package allows @componentscan annotations to be used without specifying the Basepackage attribute. If the main class is in the root package, you can also use @SpringBootApplication annotations.

The following is a typical structure:

The Application.java file will declare the main method, as well as the basic @springbootapplication annotation

@SpringBootApplication public
class Application {public
    static void Main (string[] args) {
        Springapplication.run (Application.class, args);
    }

Spring Beans and Dependency injection (Dependency injection)

You are free to use any standard spring framework technology to define beans and the dependencies they inject. For simplicity, we often use @ComponentScan annotations to search for beans and combine @Autowired builder injection. It is recommended that you follow the Java recommended package naming convention, using a reverse domain name (such as Com.example.project).

If you use the proposed structure organization code (put the application class under the root package), you can add @springbootapplication or @componentscan annotations without requiring any arguments. All of your application components (@Component, @Service, @Repository, @Controller, etc.) will be automatically registered as spring Beans.

The following is an example of a @Service bean that uses builder injection to get a riskassessor bean that is needed.

Package com.example.service;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Service;
@Service public
class Databaseaccountservice implements Accountservice {
    private final riskassessor Riskassessor;

    @Autowired public
    Databaseaccountservice (riskassessor riskassessor) {
    this.riskassessor = riskassessor;
    } 
    // ...
}

If the bean has only one constructor, you can ignore the @autowired.

@Service public
class Databaseaccountservice implements Accountservice {
    private final riskassessor Riskassessor;
    Public Databaseaccountservice (Riskassessor riskassessor) {
        this.riskassessor = riskassessor;
    }
    // ...
}

Notice how the builder injection is used in the above code to allow the Riskassessor field to be marked as final, which means that riskassessor follow up is immutable.

Many spring boot developers always use @Configuration, @EnableAutoConfiguration and @ComponentScan annotate their main class. Because these annotations are used so frequently, Spring boot provides a convenient @SpringBootApplication choice. @SpringBootApplication annotations are equivalent to using @Configuration for default properties, @EnableAutoConfiguration and @ComponentScan.

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.