Notes on springboot configuration file, annotation and automatic configuration principle (1)

European Union 2020-11-09 07:35:33
notes springboot configuration file annotation


One 、springboot Simple operation principle of

First ,springboot There must be a parent project , Namely maven Medium pom The

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring‐boot‐starter‐parent</artifactId>
    <version>1.5.9.RELEASE</version>
</parent>

Click the parent file launcher , It's mainly made up of a lot of dependencies

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring‐boot‐dependencies</artifactId>
  <version>1.5.9.RELEASE</version>
  <relativePath>../../spring‐boot‐dependencies</relativePath>
</parent>

He came to really manage Spring Boot All dependent versions in the application ;

It's also called Spring Boot Version of the Arbitration Center , There are a lot of definitions in it springboot The version of the dependent package introduced by the parent file -properties;

In the future, we import dependency by default and do not need to write version ;( Not in the dependencies The dependency of internal management naturally needs to declare version number )

quite a lot springboot Rely on the jar Packages are packaged into many initiators according to the application situation and function , Such as web starter , I'll introduce web starter

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring‐boot‐starter‐web</artifactId>
</dependency>

spring-boot-starter-web:
spring-boot-starter:spring-boot Scene launcher ; Helped us import web The components that the module depends on for normal operation ;
Spring Boot Extract all functional scenarios , Make one by one starters( starter ), Just introduce these... Into the project starter
All dependencies of related scenarios will be imported . You can import the initiator of any scene with any function


Main startup class

/**
 *  @SpringBootApplication  To mark a main program class , It shows that this is a Spring Boot application
 */
@SpringBootApplication
public class HelloWorldMainApplication {
    public static void main(String[] args) {
        // Spring The app starts 
        SpringApplication.run(HelloWorldMainApplication.class,args);
    }
}

@SpringBootApplication: Spring Boot Apply annotation to a class to indicate that the class is SpringBoot The main configuration class of ,SpringBoot
You should run this class main Method to start SpringBoot application ;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
      @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
      @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

@SpringBootConfiguration:Spring Boot Configuration class ;
Mark on a class , That means this is one Spring Boot Configuration class ;
@Configuration: This annotation is marked on the configuration class ;
Configuration class ----- The configuration file ; The configuration class is also a component in the container ;@Component


@EnableAutoConfiguration: Turn on the auto configuration function ;
What we need to configure before ,Spring Boot Help us automatically configure ;@EnableAutoConfiguration tell SpringBoot Open from
Dynamic configuration function ; In this way, the automatic configuration can take effect ;

@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

@AutoConfigurationPackage: Automatic configuration package
@Import(AutoConfigurationPackages.Registrar.class):
Spring The bottom notes @Import, Import a component into the container ; The imported components are created by

With the autoconfig class , It is unnecessary for us to write configuration injection function components manually ;
SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,classLoader);
Spring Boot From the classpath at startup META-INF/spring.factories In order to get EnableAutoConfiguration The specified value , take
These values are imported into the container as autoconfig classes , The autoconfig class takes effect , Help us with automatic configuration ; We used to need our own configuration
In the west , Automatic configuration classes help us ;
J2EE The overall integration solution and automatic configuration of spring-boot-autoconfigure-1.5.9.RELEASE.jar;





AutoConfigurationPackages.Registrar.class;
The main configuration class (@SpringBootApplication Class marked ) All components in the package and all subpackages below are scanned to Spring Containers ;
@Import(EnableAutoConfigurationImportSelector.class);
Import components into the container ?
EnableAutoConfigurationImportSelector: Which component selectors to import ;
Returns all components that need to be imported as full class names ; These components are added to the container ;
A lot of autoconfig classes will be imported into the container (xxxAutoConfiguration); It is to import all the components needed for this scenario into the container ,
And configure these components ;







Two 、springboot Configuration file for

SpringBoot Use a global profile , The profile name is fixed ;
•application.properties
•application.yml

Role of profile : modify SpringBoot Default for auto configuration ;SpringBoot At the bottom, we'll configure it automatically ;

YAML(YAML Ain't Markup Language)
YAML A Markup Language: It's a markup language
YAML isn't Markup Language: It's not a markup language ;
Markup language :
Previous configuration files ; Most of them use xxxx.xml file ;
YAML: Data centric , Than json、xml And so on are more suitable for configuration files ;
YAML: Configuration example





server:
  port: 8081 # Do not use tab Key indent , A colon followed by a space , Properties and values are case sensitive 

2、 How to write value
Literal : Normal value ( Numbers , character string , Boolean )
k: v: Write it literally ;
By default, strings do not need to be enclosed with single quotation marks or double quotation marks ;
"": Double quotes ; Does not escape special characters in a string ; Special characters will be used as the meaning they want to express
name: "zhangsan \n lisi": Output ;zhangsan Line break lisi
'': Single quotation marks ; Can escape special characters , The special character is only a common string data
name: ‘zhangsan \n lisi’: Output ;zhangsan \n lisi






object 、Map( Attributes and values )( Key value pair ):
k: v: On the next line, write the relationship between an object's properties and values ; Note that the indentation
The object is still k: v The way

friends:
lastName: zhangsan        
age: 20 

Inline writing

friends: {lastName: zhangsan,age: 18}

Array (List、Set):
use - Value represents an element in an array

pets:
 ‐ cat
 ‐ dog
 ‐ pig

Inline writing

pets: [cat,dog,pig]

3、 ... and 、springboot Profile Injection

person:
    lastName: hello
    age18
    boss: false
    birth2017/12/12
    maps: {k1: v1,k212}
    lists:
      ‐ lisi
      ‐ zhaoliu
    dog:
      name:  puppy
      age12

javaBean:

/**
 *  Set the value of each property configured in the configuration file , Map to this component
 * @ConfigurationProperties: tell SpringBoot Bind all the properties in this class with the relevant configuration in the configuration file ;
 *      prefix = "person": Which of the following attributes in the configuration file should be mapped one by one
 *
 *  Only this component is the component in the container , Can be provided by the container @ConfigurationProperties function ;
 *
 */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

We can import the profile processor , You will be prompted to write the configuration later

<!‐‐ Import profile processor , You will be prompted when binding the configuration file ‐‐>
<dependency>        
<groupId>org.springframework.boot</groupId>            
<artifactId>spring‐boot‐configuration‐processor</artifactId>            
<optional>true</optional>            
</dependency>

1、properties Configuration file in idea The default utf-8 It could be messy
adjustment

2、@Value Get the value and @ConfigurationProperties Get value comparison

The configuration file yml still properties They all get value ;

if , We just need to get some value in the configuration file in some business logic , Use @Value;
if , We wrote a special javaBean To map with the configuration file , We'll just use it @ConfigurationProperties;

3、 Configuration file injection value data verification

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
    /**
     * <bean class="Person">
     *      <property name="lastName" value=" Literal /${key} From environment variables 、 Get the value in the configuration file /#
{SpEL}"></property>
     * <bean/>
     */
   //lastName Must be in email format 
    @Email
    //@Value("${person.last‐name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

4、@PropertySource&@ImportResource&@Bean
@PropertySource: Load the specified configuration file ;

/**
 *  Set the value of each property configured in the configuration file , Map to this component
 * @ConfigurationProperties: tell SpringBoot Bind all the properties in this class with the relevant configuration in the configuration file ;
 *      prefix = "person": Which of the following attributes in the configuration file should be mapped one by one
 *
 *  Only this component is the component in the container , Can be provided by the container @ConfigurationProperties function ;
 *  @ConfigurationProperties(prefix = "person") Get the value from the global configuration file by default ;
 *
 */
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {
    /**
     * <bean class="Person">
     *      <property name="lastName" value=" Literal /${key} From environment variables 、 Get the value in the configuration file /#
{SpEL}"></property>
     * <bean/>
     */
   //lastName Must be in email format 
   // @Email
    //@Value("${person.last‐name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;

@ImportResource: Import Spring Configuration file for , Let the content in the configuration file take effect ;
Spring Boot There's no Spring Configuration file for , Our own configuration file , It doesn't automatically recognize ;
Want to make Spring The configuration file of is valid , Loading in ;@ImportResource Mark on a configuration class

@ImportResource(locations = {"classpath:beans.xml"})
Import Spring The configuration file for

Not to write Spring Configuration file for

<?xml version="1.0" encoding="UTF‐8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema‐instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring‐beans.xsd">
    <bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
</beans>

SpringBoot Recommended ways to add components to a container ; It is recommended to use full annotation
1、 Configuration class @Configuration------>Spring The configuration file
2、 Use @Bean Add components to the container

/**
 * @Configuration: Indicates that the current class is a configuration class ; Is to replace the previous Spring The configuration file
 *  Use... In the configuration file <bean><bean/> Tag add components
 *
 */
@Configuration
public class MyAppConfig {
    // Add the return value of the method to the container ; This component in the container defaults to id It's the method name 
    @Bean
    public HelloService helloService02(){
        System.out.println(" Configuration class @Bean Added components to the container ...");
        return new HelloService();
    }
}

4、 Placeholder for profile
1、 random number

${random.value}${random.int}${random.long}
${random.int(10)}${random.int[1024,65536]}
person.last‐name= Zhang San ${random.uuid}
person.age=${random.int}
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog
person.dog.age=15

5、Profile
1、 many Profile file
When we write the main configuration file , The filename can be application-{profile}.properties/yml
By default application.properties Configuration of ;
2、yml Support multi document block mode



server:
  port8081
spring:
  profiles:
    active: prod
‐‐‐
server:
  port8083
spring:
  profiles: dev
‐‐‐
server:
  port8084
spring:
  profiles: prod  # Specify which environment 

3、 Activate assignment profile
1、 Specified in the configuration file spring.profiles.active=dev
2、 Command line :
java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev;
You can test it directly , Configure the incoming command line parameters
3、 Virtual machine parameters ;
-Dspring.profiles.active=dev





6、 Configuration file loading location

springboot Startup will scan the following locations application.properties perhaps application.yml File as Spring boot The default profile for
Pieces of
–file:./config/
–file:./
–classpath:/config/
–classpath:/
Priority from high to low , High priority configuration overrides low priority configuration ;
server:
  port: 8081
spring:
  profiles:
    active: prod
‐‐‐
server:
  port: 8083
spring:
  profiles: dev
‐‐‐
server:
  port: 8084
spring:
  profiles: prod  # Specify which environment
SpringBoot The main configuration file will be loaded from all four locations ; Complementary configuration ;
We can also go through spring.config.location To change the default profile location
After the project is packaged , We can use the form of command line arguments , When starting a project, specify the new location of the configuration file ; Specify the configuration file and the default
Recognize that the loaded configuration files work together to form a complementary configuration ;
java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --spring.config.location=G:/application.properties

























7、 External configuration loading order

SpringBoot You can also load the configuration from ; Priority from high to low ; The high priority configuration covers the low priority configuration , All configurations will
Form complementary configuration
1. Command line arguments
All configurations can be specified on the command line
java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --server.port=8087 --server.context-path=/abc
Multiple configurations are separated by spaces ; -- Configuration item = value
2. come from java:comp/env Of JNDI attribute
3.Java System attribute (System.getProperties())
4. Operating system environment variables
5.RandomValuePropertySource Configured random.* Property value
from jar Bag out jar Search inside the bag ;
Priority loading band profile
6.jar The outside of the bag application-{profile}.properties or application.yml( belt spring.profile) The configuration file
7.jar Inside the bag application-{profile}.properties or application.yml( belt spring.profile) The configuration file
Load again without profile
8.jar The outside of the bag application.properties or application.yml( No spring.profile) The configuration file
9.jar Inside the bag application.properties or application.yml( No spring.profile) The configuration file
10.@Configuration On the annotation class @PropertySource
11. adopt SpringApplication.setDefaultProperties Default properties specified
All supported configuration loading sources ;


















8、 Auto configuration principle

What the configuration file can write ? How to write ? Auto configuration principle ;

1、 Auto configuration principle :
1)、SpringBoot Load the main configuration class at startup , Automatic configuration is enabled @EnableAutoConfiguration
2)、@EnableAutoConfiguration effect :
utilize EnableAutoConfigurationImportSelector Import some components into the container ?
You can see selectImports() Contents of the method ;
List configurations = getCandidateConfigurations(annotationMetadata, attributes); Get the candidate configuration




Every one of these xxxAutoConfiguration Class is a component of a container , All added to container ; Use them for automatic configuration ;
3)、 Each auto configuration class can be configured automatically ;
4)、 With HttpEncodingAutoConfiguration(Http Code auto configuration ) For example, explain the principle of automatic configuration ;

@Configuration   // Indicates that this is a configuration class , The configuration files written before are the same , You can also add components to the container 
@EnableConfigurationProperties(HttpEncodingProperties.class)  // Start... For the specified class 
ConfigurationProperties function ; Set the corresponding value in the configuration file with HttpEncodingProperties Bind up ; And put
HttpEncodingProperties Add to ioc In the container
@ConditionalOnWebApplication //Spring Bottom @Conditional annotation (Spring Annotated edition ), According to different conditions , If 
Meet the specified conditions , The configuration in the entire configuration class will take effect ;     Determine whether the current application is web application , If it is , The current configuration class takes effect
@ConditionalOnClass(CharacterEncodingFilter.class)  // Determine whether the current project has this class 
CharacterEncodingFilter;SpringMVC Filter to solve the garbled code in ;
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing =
true)  // Determine whether a configuration exists in the configuration file   spring.http.encoding.enabled; If it doesn't exist , Judgment is also true 
// Even if we don't configure pring.http.encoding.enabled=true, It also takes effect by default ;
public class HttpEncodingAutoConfiguration {
 
   // He has been with SpringBoot The configuration file of is mapped  
   private final HttpEncodingProperties properties;
// There is only one case where there is a parameter constructor , The value of the parameter is taken from the container 
   public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {  
this.properties = properties;        
}    
 
    @Bean   // Add a component to the container , Some values for this component need to be from properties In order to get 
@ConditionalOnMissingBean(CharacterEncodingFilter.class) // Determine that the container does not have this component ?    
public CharacterEncodingFilter characterEncodingFilter() {    
CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();        
filter.setEncoding(this.properties.getCharset().name());        
filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));        
filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));        
return filter;        
} 

Judge according to different conditions , Determine whether the configuration class is effective ?
Once this configuration class takes effect ; This configuration class will add various components to the container ; The properties of these components are from the corresponding properties Get in class
Of , Each property in these classes is bound to the configuration file ;
5)、 All the properties that can be configured in the configuration file are in xxxxProperties Class ‘; The configuration file can refer to a certain function as long as it can be configured
The corresponding property class



@ConfigurationProperties(prefix = "spring.http.encoding")  // Get the specified values and... From the configuration file bean Of 
Sex binding
public class HttpEncodingProperties {
   public static final Charset DEFAULT_CHARSET = Charset.forName("UTF‐8");

quintessence :
1)、SpringBoot Startup loads a large number of autoconfig classes
2)、 Let's see if there are any functions we need SpringBoot Auto configuration class written by default ;
3)、 Let's see what components are configured in this auto configuration class ;( As long as the components we want to use are , We don't need to configure it again )
4)、 When adding components to the container's auto configuration class , From properties Class to get some properties . We can specify this in the configuration file
The value of some attributes ;
xxxxAutoConfigurartion: Automatic configuration class ;
Add components to the container






xxxxProperties: Encapsulate the properties in the configuration file ;
2、 details
1、@Conditional Derived annotations (Spring The annotated version is original @Conditional effect )
effect : Must be @Conditional The specified conditions hold , Add components to the container , All the contents in the configuration configuration will take effect ;


The autoconfig class can only take effect under certain conditions ;
How do we know which autoconfig classes work ;
We can use debug=true attribute ; To have the console print the autoconfiguration report , In this way, we can easily know which automatic configuration
Class effective ;


=========================
AUTO‐CONFIGURATION REPORT
=========================
Positive matches:( Autoconfig class enabled )
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
   DispatcherServletAutoConfiguration matched:
    ‐ @ConditionalOnClass found required class
'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find
unwanted class (OnClassCondition)
      ‐ @ConditionalOnWebApplication (required) found StandardServletEnvironment
(OnWebApplicationCondition)
       
   
Negative matches:( Has not started , No autoconfig classes matched successfully )
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
   ActiveMQAutoConfiguration:
      Did not match:
         ‐ @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory',
'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)
   AopAutoConfiguration:
      Did not match:
         ‐ @ConditionalOnClass did not find required classes
'org.aspectj.lang.annotation.Aspect''org.aspectj.lang.reflect.Advice' (OnClassCondition)

 

版权声明
本文为[European Union]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云