Spring Boot common configuration

Overview

    This article mainly writes some common configurations of Spring Boot.


 

Spring Boot basic configuration

    Entry class:

        Spring Boot usually has an entry class named *Application, and the entry class has a main method. This main method is actually the entry method of a standard Java application. Use SpringApplication.run(*Application.class, args) in the main method to start the Spring Boot application project.

    @SpringBootApplication:

        @SpringBootApplication is the core annotation of Spring Boot. It is a combined annotation. The source code is as follows:

 1 //
 2 // Source code recreated from a .class file by IntelliJ IDEA
 3 // (powered by Fernflower decompiler)
 4 //
 5 
 6 package org.springframework.boot.autoconfigure;
 7 
 8 import java.lang.annotation.Documented;
 9 import java.lang.annotation.ElementType;
10 import java.lang.annotation.Inherited;
11 import java.lang.annotation.Retention;
12 import java.lang.annotation.RetentionPolicy;
13 import java.lang.annotation.Target;
14 import org.springframework.context.annotation.ComponentScan;
15 import org.springframework.context.annotation.Configuration;
16 
17 @Target({ElementType.TYPE})
18 @Retention(RetentionPolicy.RUNTIME)
19 @Documented
20 @Inherited
21 @Configuration
22 @EnableAutoConfiguration
23 @ComponentScan
24 public @interface SpringBootApplication {
25     Class<?>[] exclude() default {};
26 
27     String[] excludeName() default {};
28 }
SpringBootApplication source code

        The @SpringBootApplication annotation mainly combines @Configuration, @EnableAutoConfiguration, @ComponentScan; if you do not use the @SpringBootApplication annotation, you can directly use @Configuration, @EnableAutoConfiguration, @ComponentScan on the entry class.

        Among them, @EnableAutoConfiguration allows Spring Boot to automatically configure the current project according to the jar package dependencies in the classpath. For example, adding the spring-boot-starter-web dependency will automatically add the dependencies of Tomcat and Spring MVC, then Spring Boot will automatically configure Tomcat and Spring MVC.

        Spring Boot will automatically scan the sibling package of the class where @SpringBootApplication is located and the beans in the lower package. It is recommended that the entry class be placed under the package name of the groupId+arctifactID combination.

    Turn off specific autoconfiguration:

 

        As can be seen from the source code of @SpringBootApplication above, the exclude parameter annotated with @SpringBootApplication should be used to close specific auto-configuration, for example: @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}).

    Banner:

        Banner is a startup pattern displayed when Spring Boot starts, and we can modify or close it.

        Modify Banner:

            Just create a new banner.txt under scr/main/resources and write the pattern you want in it.

        Close Banner:

1  // There are two ways to close the Banner, both of which are to modify the content in main.
2          // 1: 
3          new SpringApplicationBuilder(Ch623Application. class ).showBanner( false ).run(args);
 4          // 2: 
5          SpringApplication springApplication = new SpringApplication(Ch623Application. class );
 6          springApplication.setShowBanner( false );
 7          springApplication.run(args);
Close Banner

 

    Spring Boot configuration file:

        Spring Boot uses a global configuration file application.properties or application.yml placed in the src/main/resources directory or under /config on the classpath.

        Spring Boot not only supports regular properties configuration files, but also yaml language configuration files. Yaml is a data-centric language with object-oriented features when configuring data.

        The role of Spring Boot's global configuration file is to modify the configuration values ​​of some default configurations.

        Example: modify the default port number of Tomcat, and modify the default access path "/" to "/helloboot", you can add the following code to the configuration file.

            server.port=9090

            server.CONTEXT_PATH=/helloboot

    starter pom:

        Spring Boot provides us with a starter pom that simplifies most scenarios of enterprise-level development. As long as the starter pom required by the application scenario is used, the related technical configuration will be eliminated, and the automatically configured Bean provided by Spring Boot can be obtained for us. .

        You can go to the Spring Boot official website to find out which starter poms it provides.

    Use xml configuration:

        Spring Boot advocates zero configuration, that is, no xml configuration, but in actual projects, there may be some special requirements that you must use xml configuration. At this time, we can load the xml configuration through @ImportResource provided by Spring.

        例:@ImportResource({"classpath:som-context.xml","classpath:another-context.xml"})

 

Spring Boot external configuration

    In addition to the above configuration, Spring Boot also allows the use of properties files, yaml files or command line parameters as external configuration.

    Command line parameter configuration:

        Spring Boot can be run based on jar packages, and the programs that are packaged into jar packages can be run directly through the command: java -jar xx.jar.

        You can modify the Tomcat port number with the command: java -jar xx.jar --server.port=9090.

    General property configuration:

        In Spring, you can inject the value in the properties file, use @PropertySource to specify the location of the properties file, and then inject the value through the @Value annotation.

        In Spring Boot, we only need to define properties in application.properties and use @Value injection directly.

        E.g:

1  // Write the following code in application.properties
 2      // book.author=gaof
 3      // book.name=spring boot
 4      // Then inject. 
5      @Value("${book.author}" )
 6      private String bookAuthor;
 7      @Value("${book.name}" )
 8      private String bookName;

    Type-safe configuration (based on properties):

        The use of @Value to inject each configuration above will be particularly troublesome in actual projects, because our configuration usually has many, and if we use the above method, we need to use @Value to inject many times.

        Spring Boot also provides a type-safe configuration method, which associates the properties attribute with a bean and its properties through @ConfigurationProperties to achieve type-safe configuration.

        E.g:

1  package com.wisely.ch6_2_3.config;
 2  
3  import org.springframework.boot.context.properties.ConfigurationProperties;
 4  import org.springframework.stereotype.Component;
 5  
6  /** 
7  * write as follows in application.properties Code
 8  * author.name=gaof
 9  * author.age=32
 10  * Then use the prefix annotated with @ConfigurationProperties to specify the prefix configured in properties.
11  * 
 12  * If you need to specify other configuration files, you need to add the attribute locations.
13   */ 
14  @Component
 15 @ConfigurationProperties(prefix = "author" )
16 //@ConfigurationProperties(prefix = "author", locations = {"classpath:config/author.properties"})
17 public class AuthorSettings {
18     private String name;
19     private Long age;
20 
21     public String getName() {
22         return name;
23     }
24 
25     public void setName(String name) {
26         this.name = name;
27     }
28 
29     public Long getAge() {
30         return age;
31     }
32 
33     public void setAge(Long age) {
34         this.age = age;
35     }
36 }

 

log configuration

    Spring Boot supports Java Util Logging, Log4J, Log4J2, and Logback as logging frameworks. No matter which logging framework is used, Spring Boot has already configured the console output and file output of the current logging framework.

    By default, Spring Boot uses Logback as the logging framework.

    Configure log level: logging.level.org.springframework.web=DEBUG; format: logging.level.packagename=level.

    Configure the log file: logging.file=D:/mylog/log.log.

Profile configuration

    Profile is used by Spring to support different configurations for different environments. The global Profile configuration uses application-{profile}.properties.

    The active Profile is specified by setting spring.profiles.active=prod in application.properties.

    E.g:

        

        

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325128977&siteId=291194637