Personal Blog:aaatao66.github.io/
Development environment:
- win10
- jdk1.8
- idea2019
- Maven 3.2.5
- Spring Boot v2.1.5.RELEASE
1. Syntax overview of YML files:
person:
lastNAME: carson
age: 18
boss: true
birth: 1234/ 12/12
{k: v,k2: v2}
maps: {k1: v1,k2: v2}
# array: - value
lists:
- lisi
- zhangsan
- wangwu
- zhaoliu
dog:
name: The dog
age: 3
spring:
mvc:
view:
prefix: /WEB-INF/views/
suffix: .jsp
datasource:
url: jdbc:mysql:///ssm
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
server:
port: 9090
Copy the code
2. Compare the @Value Value to the @configurationProperties Value
@ConfigurationProperties | @Value | |
---|---|---|
Batch injection of properties in the configuration file | function | Designate one by one |
support | Loosely bound (loosely syntactically) case | Does not support |
Does not support | SpEL expression | support |
support | JSR303 data verification | Does not support |
support | Complex type encapsulation | Does not support |
The value can be obtained either way:
- If we just need to get a Value from a configuration file for some business logic, use @value
- If we write a javaBean specifically to map to the configuration file; @ConfigurationProperties
@Validated
@Value
@Getter@Setter
@ToString
@Component
//@ConfigurationProperties (prefix = "person")
@Validated // To verify the data, if the data is abnormal, the unified exception will be thrown, convenient exception center unified processing.
public class Person {
// @Email
@Value("${person.lastNAME}")
private String lastNAME;
@Value("# {3 * 3}")
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
}
Copy the code
3. @PropertySource&@ImportResource
Because @ConfigurationProperties is a global annotation, if you want to specify it
- @propertysource: can specify a file @propertysource (“classpath: xxx.properties)
ImportResource: Import the Spring configuration file to make the contents of the configuration file take effect
- Create a HelloService class
- If there are no annotations
<?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.carson.springboot.service.impl.HelloService"></bean>
</beans>
Copy the code
@Autowired
ApplicationContext ioc;
@Test
public void testHelloService(a){
// Whether to include the bean
boolean b = ioc.containsBean("helloService");
System.out.println(b);//false
}
Copy the code
False Indicates that there is no Spring configuration file in Spring Boot, and the configuration file written by ourselves cannot be automatically identified
If you want Spring configuration files to work, load them in. Just annotate @importResource on a configuration class
- The main class
@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); }}Copy the code
@Autowired
ApplicationContext ioc;
@Test
public void testHelloService(a){
// Whether to include the bean
boolean b = ioc.containsBean("helloService");
System.out.println(b);//true
}
Copy the code
SpringBoot recommends adding components to containers:
Using the @ Bean
- 1. Configuration class ======Spring configuration file
- Create a config package for the configuration class MyAppConfig
/ * * *@Configuration: indicates that the current class is a configuration class; This is to replace the previous Spring configuration file * * that used the <bean></bean> tag to add components */
@Configuration
public class MyAppConfig {
// Add the return value of the method to the container. The default ids of the components in the container are the method names
@Bean
public HelloService helloService(a){
return newHelloService(); }}Copy the code
Remember to remove the @importResource annotation from the main class!
The following output is displayed:. ____ ____ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \ / _ ` | \ \ \ \ \ \ / ___) | | _) | | | | | | | (_ | |))))' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.5. RELEASE) the 2019-06-29 16:53:48. 11084-081 the INFO [main] C.C.S.S pringbootApplicationTests: Starting SpringbootApplicationTests on DESKTOP-JBSD6AK with PID 11084 (started by My in F:\code\springboot) 2019-06-29 16:53:48. 11084-083 the INFO [main] C.C.S.S pringbootApplicationTests: No active profile set, falling back to default profiles: Default 16:53:52 2019-06-29. 11084-689 the INFO [main] O.S.S.C oncurrent. ThreadPoolTaskExecutor: Initializing ExecutorService 'applicationTaskExecutor'11084-2019-06-29 16:53:53. 988 INFO [main] C.C.S.S pringbootApplicationTests: Started SpringbootApplicationTests in 7.259 seconds (JVM running for 10.759) true 16:53:54 2019-06-29. 11084-433 the INFO [ Thread-3] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
Copy the code
Is also true
4. ${} in configuration files
The random number
${random.value}
${random.int}
${random.long}
${random.int(10)}
The ${random. Int [1024655] 36}
Copy the code
${} gets the previously configured value
person:
lastNAME: bob${random.uuid}
age: ${random.int}
boss: true
birth: 1234/ 12/12
maps: {k1: v1,k2: v2}
lists:
- lisi
- zhangsan
- wangwu
- zhaoliu
dog:
name: ${person.lastNAME}_dog
age: 3
Copy the code
if
dog:
name: ${person.lastNAME}_dog
Copy the code
If lastNAME doesn’t exist, then
dog:
name: ${person.lastNAME:hello}_dog
Copy the code
5. Profile
5.1 Multiple Profile Files
Profile is Spring’s support for providing different configuration functions for different environments. You can quickly switch environments by specifying parameters
For example, I configured 3 ports, one default, dev(development) and prod(test).
Master configuration file names can be application. Yml/application properties
The application. Yml configuration is used by default;
5.2 YML multi-document blocks
Separate documents with — fast
spring:
profiles:
active: dev
server:
port: 9090
---
server:
port: 9091
spring:
profiles: dev
---
server:
port: 9092
spring:
profiles: prod
Copy the code
- Active: specifies which document is fast
- Profiles: Specifies a name that is identified by active
5.3 Activating a Profile
1, specify spring.profiles.active=dev in the configuration file
2, command line:
Add run > Edit > Program arguments to idea function bar
–spring.profiles.active=prod
–spring.profiles.active=dev
3. Jar the project in CMD
Java-jar (jar package name) –spring.profiles. Active =prod
4. Vm parameters:
Run > Edit >VM Options in the IDEA function bar
-Dspring.profiles.active=prod/dev
6. Load the Spring Boot configuration file
The Spring Boot startup scans the application.yml or application.properties file at the following location as the default configuration file
- file: ./config/
- file: ./
- classpath: ./config/
- classpath: /
In order of priority, all configuration files are loaded, and the high-priority configuration overrides the low-priority configuration
File: indicates a directory at the same level as SRC
Classpath: resources directory
We can also change the default configuration file location by configuring spring.config.location:
1. Package your project
2. Format of the command line: Java – jar package name — spring. Config. Location = F: / app/application. The properties (the absolute path to the configuration file)
After the project is packaged, some configurations may need to be changed later, so you can use this approach, and the old configuration will still exist and the new configuration will be applied
7. Load sequence of external configuration
SpringBoot can also load configurations from the following locations, from high priority to low priority, high priority overrides low priority, and if there are different configurations, they complement each other
-
Command line arguments
java -jar xxx.jar –server.port=8081 –xxx
Multiple configurations are separated by Spaces: — XXX — XXX
-
NDI attributes from Java :comp/env
-
Java System Properties(system.getProperties ())
-
Operating system environment variables
-
RandomValuePropertySource configuration of the random. * attribute values
Find inside jar from outside jar:
Those with profiles are loaded preferentially
- Application -{profile}. Properties or application.yml(with spring.profile) configuration file in the “outside” part of the JAR package
- Application -{profile}. Properties or application.yml(with spring.profile) configuration file in the “inside” part of the JAR package
Then load the profile without it
- Application. Properties or Application. Yml (without Spring.profile) configuration file for the “outside” part of the JAR package
- Application. Properties or application. Yml (without spring.profile) configuration file for the “inside” part of the JAR package
There are others:
- @Configuration Annotation @propertysource on the class
- Through SrpingApplication. SetDefaultProperties specify a default properties
See chapter 24 of the official documentation for details
8. Principle of automatic configuration (key)
What exactly can autoconfiguration do? How to write? Automatic configuration principle:
The document address
See x. Appendices in the last chapter of the directory
It tells you what the configuration items are
In fact:
- 1.SpringBoot launches load a large number of auto-configuration classes
- 2. Let’s see if the functionality we need is automatically configured by default in SpringBoot
- 3. Let’s take a look at what components are configured in this auto-configuration class. (As long as the components we want to use have, we don’t need to configure them.)
- 4. When adding a component to the auto-configuration class in the container, we get some properties from the Properties class. We can specify the values of these properties in the configuration file
XxxxAutoConfigurartion: automatic configuration class;
Add components to the container
XxxxProperties: Encapsulates the related properties in the configuration file;
Skills:
Idea Double-click Shift to search *AutoConfiguration
Click on automatic configuration related to cache
We will see the following source code:
@EnableConfigurationProperties({CacheProperties.class})
@AutoConfigureAfter({CouchbaseAutoConfiguration.class, HazelcastAutoConfiguration.class, HibernateJpaAutoConfiguration.class, RedisAutoConfiguration.class})
@Import({CacheAutoConfiguration.CacheConfigurationImportSelector.class})
public class CacheAutoConfiguration {
public CacheAutoConfiguration(a) {}Copy the code
CTRL + left mouse click:
@EnableConfigurationProperties({CacheProperties.class})
/ / click CacheProperties
Copy the code
We’ll see on the CacheProperties class:
@ConfigurationProperties(
prefix = "spring.cache"
)
public class CacheProperties {
Copy the code
Prefix = “spring.cache” : is the syntactic prefix in the yML /properties configuration file
What specific things can be configured?
It is these
Or you can use the idea code to prompt in the configuration file, such as I call the first getType
So that’s the source code way to see what we can configure in a configuration file, right
Let’s say I want to connect to a database, so LET me search
I see the fields we need, and many of the methods below (no screenshots here).
The next step is to configure the configuration file:
Details of 9.
@conditional derives annotations
It is essentially using the @Conditional annotation underlying Spring
Action: Only if @Conditional conditions are true can a component be added to the container, the contents of the configuration class take effect; if false is returned, the configuration will not take effect
SpringBoot extends @Conditional annotations such as:
How do we know which classes are working and which are not? Simply add:
debug: true
Copy the code
Then run our vermilion class:
We’ll see:
There are: