Spring Boot is based on conventions, so many configurations have default values, but if you want to replace the default with your own configuration, This can be configured using application.properties or application.yml (application.yaml). By default, SpringBoot loads the application.properties or application.yml(application.yaml) file in the resources directory. The priority of the configuration file is.properties >.yaml >.yml according to the file reading order in the spring-boot-starter-parent
<excludes>
<exclude>**/application*.yml</exclude>
<exclude>**/application*.yaml</exclude>
<exclude>**/application*.properties</exclude>
</excludes>
Copy the code
I. YAML configuration file
1. Configure common data
name: lisi
Copy the code
Ps: value has a space before it, and a space between the key and the value
Strings are not quoted by default:
“” : double quotation marks: Special characters in the string are not escaped, they are used as their intended meanings:
Name: “zhangsan \n lisi” ==> Output: zhangsan newline lisi
“: single quote: escapes special characters, which end up being just plain string data:
Name: ‘zhangsan \n lisi’ ==> Output: zhangsan \n lisi
2. Configure object data and Map data
Person: {name: zhangsan age: 18,addr: Shanghai} person: {name: zhangsan age: 18,addr: Shanghai}Copy the code
Ps: the number of Spaces to indicate the hierarchy, the same indent on behalf of the same level
3. Configure the array (List and Set) data
City: - Beijing - tianjin - Shanghai - chongqing # or city: [Beijing, tianjin, Shanghai, chongqing] # collection element is the object in the form to the student: - name: zhangsan age: 18 score: 100 - name: lisi age: 28 score: 88 - name: wangwu age: 38 score: 90Copy the code
Ps: There is a space between value and –
Common SpringBoot configurations
# QUARTZ SCHEDULER (QuartzProperties) spring.quartz.jdbc.initialize-schema=embedded # Database schema initialization mode. spring.quartz.jdbc.schema=classpath:org/quartz/impl/jdbcjobstore/tables_@@platform@@. sql # Path to the SQL file to use to initialize the database schema. spring.quartz.job-store-type=memory # Quartz job store type. spring.quartz.properties.*= # Additional Quartz Scheduler properties. # ---------------------------------------- # WEB PROPERTIES # ---------------------------------------- # EMBEDDED SERVER CONFIGURATION (ServerProperties) server.port=8080 # Server HTTP port. server.servlet.context-path= # Context path of the application. server.servlet.path=/ # Path of the main dispatcher servlet. # HTTP encoding (HttpEncodingProperties) spring.http.encoding.charset=UTF-8 # Charset of HTTP requests and responses. Added to the "Content-Type" header if not set explicitly. # JACKSON (JacksonProperties) spring.jackson.date-format= # Date format string or a fully-qualified date format class name. For instance, `yyyy-MM-dd HH:mm:ss`. # SPRING MVC (WebMvcProperties) spring.mvc.servlet.load-on-startup=-1 # Load on startup priority of the dispatcher servlet. spring.mvc.static-path-pattern=/** # Path pattern used for static resources. spring.mvc.view.prefix= # Spring MVC view prefix. spring.mvc.view.suffix= # Spring MVC view suffix. # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.driverClassName=### spring.datasource.url= # JDBC URL of the database. spring.datasource.password= # Login password of the database. spring.datasource.username= # Login username of the database. # JEST (Elasticsearch HTTP client) (JestProperties) spring.elasticsearch.jest.password= # Login password. spring.elasticsearch.jest.proxy.host= # Proxy host the HTTP client should use. spring.elasticsearch.jest.proxy.port= # Proxy port the HTTP client should use. spring.elasticsearch.jest.read-timeout=3s # Read timeout. spring.elasticsearch.jest.username= # Login username.Copy the code
2. Configuration files
1. Use the @value annotation to map
We can use the @value annotation to map the values in the configuration file to the fields of a Spring-managed Bean
application.yml person: name: zhangsan age: 18 addr: =================== @RestController public class QuickController {@value ("${person. Name}") private String name; @Value("${person.age}") private int age; @Value("${person.addr}") private String addr; @requestMapping ("/ymlTest") public String ymlTest(){return "SpringBoot successfully accessed. Name :" + name + ", age :" + age + ", address :" + addr "; }Copy the code
2. Use the @ConfigurationProperties annotation to map
Configationproperties (prefix=” prefix of key in the configuration file “) can be automatically mapped to entities.
Also, the class must be in the container (decorated with @Component, @Controller annotations)
// Person class @getter @setter @ToString @Component @ConfigurationProperties(prefix = "Person ") public class Person {public String name; public Integer age; public Boolean boss; public Date birth; public String nickName; public Map<String,Object> maps; public List<Object> lists; public Dog dog; }Copy the code
## Application. yml person: Name: Name Age: 22 Boss: false Birth: 1999/09/30 Maps: {k1: blogs,k2: share.com} lists: [123,625,342,803] Dog: Name: Little black age: 4 nick-name: RainingCopy the code
Configuration file Configuration-Functions of the processor
<! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>Copy the code
In the entity class, use the @ConfigurationProperties annotation to declare prefix first. When writing the YML configuration file, enter the corresponding prefix and you will be prompted for the properties in the entity class.
test
@RunWith(SpringRunner.class) @SpringBootTest class SpringBootReturn02ApplicationTests { @Autowired Person person; @Test public void contextLoads() { System.out.println(person); }}Copy the code
Garbled characters appear in the application. Properties file
Reason: IDEA uses UTF-8 encoding, peoperties uses ASCII
File –> Setting
3. Comparison of @value and @ConfigurationProperties
@ConfigurationProperties | @Value | |
---|---|---|
function | Batch injection of properties in the configuration file | Specify one by one |
Loose binding (loose syntax, hump, bars) | support | Does not support |
SpEL | Does not support | support |
JSR303 data verification | support | Does not support |
Complex type encapsulation (Map, object) | support | Does not support |
JSR303 Data validation (@ConfigurationProperties as an example)
-
Import dependence
<dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> < version > 6.1.5. Final < / version > < / dependency >Copy the code
-
Annotate the validation class
@Getter @Setter @ToString @Component @ConfigurationProperties(prefix = "person") @Validated public class Person { @Email public String name; public Integer age; public Boolean boss; public Date birth; public String nickName; public Map<String,Object> maps; public List<Object> lists; public Dog dog; }Copy the code
-
test
4. @ PropertySource with @ ImportResource
@propertysource (yML profiles are not supported by default! So old utility Properties)
Name = deadpool person.age=24 person.boss=false person.birth=1998/3/23 person.maps.k1= points Lists =a,s,d person.dog. Name = small white person.dog. Age =3 person.nick-name= small meanCopy the code
@Getter @Setter @ToString
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
public String name;
public Integer age;
public Boolean boss;
public Date birth;
public String nickName;
public Map<String,Object> maps;
public List<Object> lists;
public Dog dog;
}
Copy the code
ImportResource: Import the Spring configuration file and make the contents of the configuration file effective
There is no Spring configuration file in Spring Boot, and the configuration file written by us cannot be recognized and taken effect.
To make Spring’s configuration file load and take effect: the @importResource annotation is on the configuration class
@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringBootReturn02Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootReturn02Application.class, args);
}
}
Copy the code
Spring Boot recommends ways to add components to a container: Fully annotated configuration classes are recommended
The configuration class replaces the Spring configuration file
@configuration public class MyAppConfig {@bean public HelloService HelloService (){ Case-sensitive system.out. println(" configure class to inject helloService"); return new HelloService(); }}Copy the code
/ / test class @ RunWith (SpringRunner class) @ SpringBootTest class SpringBootReturn02ApplicationTests {@ the Resource ApplicationContext ioc; @Test public void testHelloService(){ boolean b = ioc.containsBean("helloService"); // System.out.println(b); }}Copy the code
5. Placeholders for configuration files
Can be used as an undefined value in the configuration file
-
The random number
${random. Long} ${random. Long} ${random. Int (10)} ${random.Copy the code
-
Placeholder to get the value of the configuration. You can specify a default value if none is available
Person. Name = three ${random.uuid} person.age=${random.int} person.boss=false person.birth=1998/3/23 person.maps.k1= points Lists =a,s,d person.dog. Name =${person.nick-name}_ small white person.dog. Age =3 Person.nick-name =${person.hello: hello} // Specify the default valueCopy the code
6. Profile
(1). Multiple profiles
When we write the main configuration file, the file name can be application-{profile}.properties/yml
By default, the configuration of application.properties is used
(2). Yml supports multi-document fast mode
# application.yml
server:
port: 8082
spring:
profiles:
active: dev
---
server:
port: 8083
spring:
profiles: dev
---
server:
port: 8084
spring:
profiles: prod
Copy the code
(3). Activate the specified profile
-
In the main configuration file specify: spring.profiles. Active =dev
-
Command line: –spring.profiles. Active =dev
-
In the Project launch option box, go to Edit Configurations –> Program Arguments and enter –spring.profiles. Active =dev
-
Activated when you run the JAR package
Java jar – spring – the boot – return02-0.0.1 – the SNAPSHOT. Jar — spring. Profiles. The active = dev
-
-
Vm Parameters
-Dspring.profiles.active=dev
In the Project Launch options box, enter -dspring.profiles. Active =dev in the Edit Configurations –> VM Option field
7. Configure the file loading location
The Spring Boot startup scans the application.properties or application.yml file in the following locations as the default configuration file for Spring Boot.
- file:./config
- file:./
- classpath:/config
- classpath:/
— file represents the location of the project, and classpath represents the resources folder
— The configuration priorities are in descending order. The higher-priority configuration overrides the lower-priority configuration. Spring Boot loads all the master configuration files from these four locations: complementary configuration
— We can also change the default configuration by configuring –spring.config.location; After the project is packaged, use command line arguments to specify a new location for the configuration file when starting the project. The specified configuration file and the default configuration file work together to complement the configuration
Java jar - spring - the boot - return03 - config - 0.0.1 - the SNAPSHOT. Jar -- spring. Config. Location = F: / application propertiesCopy the code
8. Foreign configuration loading sequence
SpringBoot can also load configuration from the following locations; Priority from high to low; The configuration with a higher priority overrides the configuration with a lower priority. All configurations are complementary
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 properties from Java :comp/env
Java System properties (system.getProperties ())
4. Operating system environment variables
5. RandomValuePropertySource configuration of the random. * attribute values
The search is carried out from the JAR package to the JAR package;
Profiles are loaded preferentially
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
9. Application. properties or application.yml(without spring.profile) configuration file inside the jar package
10.@Configuration annotates @propertysource on the class
11. Through SpringApplication. SetDefaultProperties specify default properties
All supported configuration loading sources;
Refer to official documents
Three, logs,
1. Log framework
A logging framework on the market;
JCL, jboss-logging, logback, log4j, log4j2, slf4j….
Logging facade (the abstraction layer of logging) | The logging implementation |
---|---|
Log4j JUL (java.util.logging) Log4j2Logback |
Select a facade (abstraction layer) on the left and an implementation on the right;
Log facade: SLF4J;
Log implementation: Logback;
SpringBoot: The bottom layer is the Spring framework, which uses JCL by default.
SpringBoot uses SLF4j and logback;
2. Use SLF4J
How to use SLF4j in your systemwww.slf4j.org
In future development, logging methods should not be called directly from the logging implementation class, but from methods in the logging abstraction layer.
Import the SLF4J jar package and logback implementation JAR package into the system.
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HelloWorld { public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(HelloWorld.class); logger.info("Hello World"); }}Copy the code
Here is:
Each logging implementation framework has its own configuration file. With SLF4J, the configuration file is still its own configuration file.
2. Legacy issues
When a project integrates multiple frameworks, each of which depends on a specific logging framework, how can we use the logging framework of our choice in a unified way?
Application (SLF4j +logback) : Spring (Commons-logging), Hibernate (Jboss-logging), MyBatis, XXXX
Unified logging, even if other frameworks are using SLF4J for output with me?
How to unify all logs in a project to SLF4J:
1. Exclude other logging frameworks from the project;Copy the code
- Replacing the original logging framework with a tundish;
- We import the other implementations of SLF4J
3. Spring Boot log relationship
SpringBoot uses it for logging:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
Copy the code
Underlying relationship:
Conclusion:
-
Spring Boot also uses slF4J + Logback for logging.
-
Spring Boot also replaces other logs with SLF4J; Use intermediate replacement packages, such as log4j-to-slf4j, jul-to-slf4j;
-
If you want to introduce another framework, be sure to remove the default logging dependency for this framework
The Spring framework uses Commons-logging;
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> Copy the code
SpringBoot automatically ADAPTS all logging and uses SLF4J + Logback for logging. When other frameworks are introduced, they simply exclude the logging framework that SpringBoot depends on.
4. Log usage
1. Default Settings
By default, Spring Boot configures logs for us:
/ / test class @ SpringBootTest class SpringBootReturn05LoggingApplicationTests {/ / recorder Logger Logger = LoggerFactory.getLogger(getClass()); @test void contextLoads() {// log level // trace < debug < info < warn < error // Adjust the log level, Logger. Trace (" This is trace "); Logger.debug (" This is the debug log "); Logger.info (" this is the info log "); // The default logger.info level is not set. Logger.warn (" This is the warn log "); Logger.error (" This is the error log "); }}Copy the code
# application. Properties # Log output level Use the default level info logging.level.com.xiaojian=trace # output log springboot. # can specify the full path to the log file. Name =F:/springboot.log # if you do not specify a path, you will generate a log file in the current project #logging.file.name=F:/springboot.log # if you do not specify a path, you will create a log file in the current project # And the log subfolder, Logging.pattern. Console =%d{YYYy-MM-dd} [%thread] Loggin.pattern. File =%d{YYYY-MM-dd} === [%thread] === =% -5level === = %logger{50} === %msg%nCopy the code
logging.file | logging.path | Example | Description |
---|---|---|---|
(none) | (none) | Output in the console only | |
Specify file name | (none) | my.log | Output logs to the my.log file |
(none) | The specified directory | /var/log | Output to the spring.log file in the specified directory |
2. Specify the configuration
Assign each logging framework its own configuration file to the classpath. SpringBoot does not use its default configuration
Logging System | Customization |
---|---|
Logback | logback-spring.xml .logback-spring.groovy .logback.xml or logback.groovy |
Log4j2 | log4j2-spring.xml or log4j2.xml |
JDK (Java Util Logging) | logging.properties |
Logback. XML: is directly recognized by the logging framework;
Logback-spring. XML: The logging framework does not load log configuration items directly. SpringBoot parses the log configuration and uses the advanced Profile function of SpringBoot
<springProfile name="staging"> <! -- configuration to be enabled when the "staging" profile is active --> </springProfile>Copy the code
Using Spring Boot’s advanced Profile feature, an error will be reported if the logback. XML file is used because the springProfile is used
Configure the development environment in the application.properties or application.yml file.
<! -- logback.xml -- logback.xml -- logback.xml --> <! - ch. Qos. Logback. Core. ConsoleAppender said console output - > < appender name = "stdout" class = "ch. Qos. Logback. Core. ConsoleAppender" > <! -- Log output format: %d indicates the date and time, %thread indicates the thread name, and % -5Level indicates the level width of 5 characters from the left. %logger{50} indicates that the logger name contains a maximum of 50 characters. Otherwise, the logger name is separated by periods. % MSG: Log messages, % n is a newline -- > < layout class = "ch. Qos. Logback. Classic. PatternLayout" > < springProfile name = "dev" > < pattern > % d {yyyy - MM - dd HH:mm:ss.SSS} ->>>>>>>>>>>>>>> [%thread] %-5level %logger{50} - %msg%n</pattern> </springProfile> <springProfile name="! dev"> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} -=============== [%thread] %-5level %logger{50} - %msg%n</pattern> </springProfile> </layout> </appender>Copy the code
5. Switch the log framework
The switch can be performed according to the SLF4J log adaptation diagram.
Slf4j +log4j;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>logback-classic</artifactId>
<groupId>ch.qos.logback</groupId>
</exclusion>
<exclusion>
<artifactId>log4j-over-slf4j</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
Copy the code
Switch log4j2
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-logging</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
Copy the code