5 ways to read and configure springboot (6): Summarize the difference between properties, yml, and xml

5 ways to read configuration through springboot (1): read bean directly

5 ways to read configuration of springboot (2): read the specified file through config

5 ways to read configuration of springboot (3): read through application.properties

5 ways to read and configure springboot (4): read through application.yml

5 ways to read and configure springboot (5): read through applicationContext.xml

I summarize:

1.config read:

Need to declare @Configuration in entity class

Reading files is done via @ComponentScan()

for example:


// Scan @Configuration from the root directory by default

//Scan the specified package path
 @ComponentScan ( "springboot.config")

2. Read the application file:

.properties and .yml files are injected by adding @Value to the entity class

Reading files are done through @PropertySource()

for example:

The format of the .properties file is key=value

.yml file format is key:value


student.name = well
 student.age = 15


The configuration format of the #yml file is key:value
 student:
   name: Xiaoming
   age: 25

@Value("${student.name}")
private String name;
@Value("${student.age}")
private  int age;

//Read application.properties in the resources directory
 @PropertySource ( "classpath:application.properties" )

//Read application.yml in the resources directory
 @PropertySource ( "classpath:application.yml" )

Need to add dependencies in pom.xml:

<!-- This dependency will inject the value of the configuration file into @value-->
 <dependency>
     <groupId> org.springframework.boot </groupId>
     <artifactId> spring-boot-configuration-processor </artifactId>
 < /dependency>

3. If application.properties and application.yml are in the same resources directory, the default is to read the first configuration file

for example:


By default, the information in the application.properties file is read.

4. If there is application.properties or application.yml, you will get an error when you name the xml application.xml:

Even if I delete application.properties or application.yml it will report an error:


But when I renamed application.xml to applicationContext.xml, it worked fine.

5. ApplicationContext is read using @ImportResource

//Read applicationContext.xml in the resources directory
 @ImportResource ( "classpath:applicationContext.xml" )
My motto: No, I can learn; I fall behind, I can catch up; I fall, I can stand up; I will do it.


Guess you like

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