Spring boot related matching files

1. Profile

Spring boot uses a global configuration file with a fixed name;

•application.properties

•application.yml

The function of configuration file: modify the default value of spring boot automatic configuration; spring boot automatically configures for us at the bottom;

YAML(YAML Ain't Markup Language)

YAML A Markup Language: a markup language

YAML isn't Markup Language: not a markup language;

Markup Language:

Previous configuration files; most of them are xxxx.xml files;

YAML: data centric, more suitable for configuration files than json, xml, etc;

YAML: Configuration Example

server:
  port: 8081

XML:

<server>
	<port>8081</port>
</server>

2. YAML syntax:

1. Basic grammar

k: (space) v: indicates a pair of key value pairs (space must have);

Controls hierarchy by indenting spaces; all left aligned columns are at the same level

server:
    port: 8081
    path: /hello

Attributes and values are also case sensitive;

2. How to write values

Literal: normal value (number, string, Boolean)

k: v: write directly;

By default, strings do not need single or double quotation marks;

": double quotation marks; special characters in strings will not be escaped; special characters will be used as the meaning they want to express

name: "zhangsan \n lisi": output; zhangsan line feed lisi

': single quotation mark; it will escape special characters, which are only common string data

name: 'zhangsan \n lisi': output; zhangsan \n lisi

 

Object, Map (property and value) (key value pair):

k: v: write the relationship between the attribute and value of the object on the next line; pay attention to indenting

Object or k: v

friends:
		lastName: zhangsan
		age: 20

In line:

friends: {lastName: zhangsan,age: 18}

Array (List, Set):

Represents an element in an array with a - value

pets:
 - cat
 - dog
 - pig

In line:

pets: [cat,dog,pig]

 

3. Profile value injection

configuration file

person:
    lastName: hello
    age: 18
    boss: false
    birth: 2017/12/12
    maps: {k1: v1,k2: 12}
    lists:
      - lisi
      - zhaoliu
    dog:
      name: puppy
      age: 12

javaBean:

/**
 * Map the value of each property configured in the configuration file to this component
 * @ConfigurationProperties: Tell SpringBoot to bind all the properties in this class to the relevant configuration in the configuration file;
 *      prefix = "person": Which of the following attributes in the configuration file is mapped one by one
 *
 * Only when this component is a component in the container can the @ ConfigurationProperties function provided by the container be enabled;
 *
 */
@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 and write the configuration later

<! -- when importing the profile processor, you will be prompted when binding the profile -- >
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>

1. The default utf-8 of properties configuration file in idea may be garbled

adjustment

2. Comparison between @ Value get Value and @ ConfigurationProperties get Value

Whether the configuration file yml or properties can get values;

If so, we just need to get a Value in the configuration file in a certain business logic, and use @ Value;

If we specially write a javaBean to map with the configuration file, we will directly use @ ConfigurationProperties;

 

3. Profile injection value data verification

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {

    /**
     * <bean class="Person">
     *      <property name="lastName" value="Literal amount / ${key} get value from environment variable and configuration file / {spiel} "> < property >
     * <bean/>
     */

   //lastName must be in mailbox 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;

/**
 * Map the value of each property configured in the configuration file to this component
 * @ConfigurationProperties: Tell SpringBoot to bind all the properties in this class to the relevant configuration in the configuration file;
 *      prefix = "person": Which of the following attributes in the configuration file is mapped one by one
 *
 * Only when this component is a component in the container can the @ ConfigurationProperties function provided by the container be enabled;
 *  @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 amount / ${key} get value from environment variable and configuration file / {spiel} "> < property >
     * <bean/>
     */

   //lastName must be in mailbox format
   // @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;

@Import resource: import the Spring configuration file to make the content in the configuration file effective;

There is no Spring configuration file in Spring Boot, and the configuration file we wrote ourselves cannot be recognized automatically;

To make the Spring configuration file effective, load it in; @ ImportResource is marked on a configuration class

@ImportResource(locations = {"classpath:beans.xml"})
Import Spring's configuration file for it to take effect

 

Don't write Spring's configuration file

<?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 recommends adding components to containers; full annotation is recommended

1. Configuration class @ configuration ------ > spring configuration file

2. Use @ Bean to add components to the container

/**
 * @Configuration: Indicates that the current class is a configuration class; that is, to replace the previous Spring configuration file
 *
 * Add components with < bean > < bean / > tag in configuration file
 *
 */
@Configuration
public class MyAppConfig {

    //Add the return value of the method to the container; the default id of this component in the container is the method name
    @Bean
    public HelloService helloService02(){
        System.out.println("Configuration class@Bean Added components to container...");
        return new HelloService();
    }
}

##4. Placeholder for profile

1. Random number

${random.value},${random.int},${random.long}
${random.int(10)},${random.int[1024,65536]}

2. Placeholder gets the value configured before. If not, use: to specify the default value

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. Multiple Profile files

When we write the main configuration file, the file name can be application-{profile}.properties/yml

The configuration of application.properties is used by default;

 

2. yml supports multi document block mode

 

server:
  port: 8081
spring:
  profiles:
    active: prod

---
server:
  port: 8083
spring:
  profiles: dev


---

server:
  port: 8084
spring:
  profiles: prod  #Specify which environment to belong to

3. Activate the specified profile

1. Specify spring.profiles.active=dev in the configuration file

2. Command line:

java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev;

You can configure the incoming command line parameters directly during the test

3. Virtual machine parameters;

-Dspring.profiles.active=dev

6. Profile load location

springboot will scan the application.properties or application.yml file in the following location as the default configuration file of Spring boot

–file:./config/

–file:./

–classpath:/config/

–classpath:/

The priority is from high to the bottom. The high priority configuration will cover the low priority configuration;

Spring boot will load the main configuration file from all four locations;

 

==We can also change the default configuration file location through spring.config.location==

After the project is packaged, we can use the form of command-line parameters to specify the new location of the configuration file when starting the project; the specified configuration file and the default 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 load order

==Spring boot can also load configurations from the following locations; priority ranges from high to low; high priority configurations cover low priority configurations, and all configurations form complementary configurations==

1. Command line parameters

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. JNDI attribute from java:comp/env

3.Java system properties (System.getProperties())

4. Operating system environment variables

5. random. * property value of randomvaluepropertysource configuration

 

==Search from jar package to jar package==

==Priority loading with profile==

6. application-{profile}.properties or application.yml (with spring.profile) configuration file outside the jar package

7. application-{profile}.properties or application.yml (with spring.profile) configuration file inside the jar package

 

==Then load without profile==

8. application.properties or application.yml (without spring.profile) configuration file outside the jar package

9. application.properties or application.yml (without spring.profile) configuration file inside the jar package

 

10. @ PropertySource on the @ configuration annotation class

11. Default properties specified through SpringApplication.setDefaultProperties

All supported configuration loading sources;

8. Auto configuration principle

What can a configuration file write? How do you write it? Automatic configuration principle;

Property reference that configuration file can configure

 

1. Auto configuration principle:

1) . when SpringBoot is started, the main configuration class is loaded and the auto configuration function is enabled = = @ EnableAutoConfiguration==

2) , @ EnableAutoConfiguration role:

  • Use EnableAutoConfigurationImportSelector to import some components into the container?

  • You can view the contents of the selectImports() method;

  • List < string > configurations = getcandidate configurations (annotation metadata, attributes); get candidate configurations

  • SpringFactoriesLoader.loadFactoryNames()
    Scan META-INF/spring.factories under all jar package Classpaths
     Wrap the contents of the scanned files into properties objects
     Get the value of EnableAutoConfiguration.class class (class name) from properties and add them to the container

    ==All the values of EnableAutoConfiguration configured in META-INF/spring.factories under the classpath are added to the container==

  • # 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.batch.BatchAutoConfiguration,\
    org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
    org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
    org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
    org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
    org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
    org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
    org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
    org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
    org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
    org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\
    org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
    org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
    org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
    org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
    org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
    org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
    org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
    org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
    org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
    org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
    org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
    org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
    org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
    org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
    org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
    org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
    org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
    org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
    org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
    org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
    org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
    org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
    org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
    org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
    org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
    org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
    org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
    org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
    org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
    org.springframework.boot.autoconfigure.mobile.DeviceResolverAutoConfiguration,\
    org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration,\
    org.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfiguration,\
    org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
    org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
    org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
    org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
    org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration,\
    org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\
    org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,\
    org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,\
    org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration,\
    org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
    org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
    org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration,\
    org.springframework.boot.autoconfigure.social.FacebookAutoConfiguration,\
    org.springframework.boot.autoconfigure.social.LinkedInAutoConfiguration,\
    org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration,\
    org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
    org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
    org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
    org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
    org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
    org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration,\
    org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,\
    org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration,\
    org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration,\
    org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration,\
    org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration,\
    org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration,\
    org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration,\
    org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,\
    org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration,\
    org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration,\
    org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration

    Each such xxxAutoConfiguration class is a component in the container, which is added to the container; use them for automatic configuration;

    3) . each automatic configuration class performs automatic configuration function;

    4) Take httpencoding autoconfiguration as an example to explain the principle of autoconfiguration;

  • @Configuration   //Indicates that this is a configuration class. Like the previously written configuration file, components can also be added to the container
    @EnableConfigurationProperties(HttpEncodingProperties.class)  //Start the ConfigurationProperties function of the specified class; bind the corresponding value in the configuration file with HttpEncodingProperties; and add HttpEncodingProperties to the ioc container
    
    @ConditionalOnWebApplication //Spring underlying @ Conditional annotation (spring annotation version), according to different conditions, if the specified conditions are met, the configuration in the whole configuration class will take effect; judge whether the current application is a web application, if so, the current configuration class will take effect
    
    @ConditionalOnClass(CharacterEncodingFilter.class)  //Determine whether the current project has this type of CharacterEncodingFilter; spring MVC filter for scrambling;
    
    @ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)  //Determine whether a configuration spring.http.encoding.enabled exists in the configuration file; if not, it is also true
    //Even if pring.http.encoding.enabled=true is not configured in our configuration file, it will take effect by default;
    public class HttpEncodingAutoConfiguration {
      
      	//He has mapped the configuration file of SpringBoot
      	private final HttpEncodingProperties properties;
      
       //In the case of only one 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 of this component need to be obtained from properties
    	@ConditionalOnMissingBean(CharacterEncodingFilter.class) //Judge 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;
    	}

    According to the current different conditions, determine whether the configuration class is effective?

    Once the configuration class takes effect, it will add various components to the container. The properties of these components are obtained from the corresponding properties class, and each property in these classes is bound to the configuration file;

     

     

     

    5) All the properties that can be configured in the configuration file are encapsulated in the xxxproperties class. If the configuration file can be configured, it can refer to the property class corresponding to a function

  • @ConfigurationProperties(prefix = "spring.http.encoding")  //Get the specified value and bean property from the configuration file to bind
    public class HttpEncodingProperties {
    
       public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

     

Published 17 original articles, won praise 4, visited 20000+
Private letter follow

Tags: Spring SpringBoot xml JDBC

Posted on Fri, 13 Mar 2020 03:45:41 -0700 by Mr Tech