Home > Java > javaTutorial > body text

How does springboot read lists, arrays, map collections and objects in yml files?

PHPz
Release: 2023-05-11 10:46:10
forward
2679 people have browsed it

application.yml defines the list collection

The first way is to use the @ConfigurationProperties annotation to get all the values ​​of the list collection

type:
  code:
    status:
      - 200
      - 300
      - 400
      - 500
Copy after login

Write the entity class corresponding to the configuration file, What needs to be noted here is that to define the list collection, first define a configuration class Bean, and then use the annotation @ConfigurationProperties annotation to obtain the list collection value. Here we will explain the role of the relevant annotations.

  • @Component Hands over the entity class to Spring management

  • @ConfigurationProperties(prefix = “type.code”) Read the yml file list

  • @Data automatically generates getter and setter methods

As shown in the figure below

package com.o2o.data;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Component
@ConfigurationProperties(prefix = "type.code") // 配置文件的前缀
@Data
public class TypeCodeConfig {
    private List<String> status;

    public void setStatus(List<String> status){
        this.status = status;
    }
    public List<String> getStatus(){
        return status;
    }
}
Copy after login

Then where to use For automatic injection, I read this list directly in the startup class. It should be noted that using the list configured in yml requires injecting the object first, and then reading the value in the configuration file through the get method.

  • @Autowired private TypeCodeConfig typeCodeConfig; Use annotations to inject objects

  • System.out.println(typeCodeConfig.getStatus()); Call getter Method to read the value

package com.o2o;

import com.o2o.data.TypeCodeConfig;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@MapperScan("com.o2o.mapper")
public class AutoTestApplication implements CommandLineRunner {

	public static void main(String[] args) {
		SpringApplication.run(AutoTestApplication.class, args);
	}

	@Autowired
	private TypeCodeConfig typeCodeConfig;

	@Override
	public void run(String... args) throws Exception {
		System.out.println(typeCodeConfig.getStatus());
Copy after login

Start springboot We have successfully read all the values ​​of the list collection in the yml file from the console

How does springboot read lists, arrays, map collections and objects in yml files?

The second method uses the @value annotation to obtain all the values ​​​​of the list collection

The yml file is configured as follows

student:
  ids:
    - 7
    - 8
    - 9
Copy after login

Then create an entity class

@Data
public class Student {
    @Value("${student.ids}")
    private List<Integer> ids;

}
Copy after login

Create a new configuration class for the list attribute

@Component
@ConfigurationProperties(prefix = "student")
@Data
public class TypeCodeConfig {

private List<Integer> ids;

   public void setIds(List<Integer> ids) {
       this.ids = ids;
   }
      public  List<Integer> getIds(){
       return ids;
}
Copy after login

Inject in the startup class

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@MapperScan("com.o2o.mapper")
public class AutoTestApplication implements CommandLineRunner {

	public static void main(String[] args) {
		SpringApplication.run(AutoTestApplication.class, args);
	}

	@Autowired
	private TypeCodeConfig typeCodeConfig;
	
	@Override
	public void run(String... args) throws Exception {

		System.out.println(typeCodeConfig.getIds());
	}
Copy after login

Start springboot and we have successfully read all the values ​​​​of the list collection in the yml file from the console

How does springboot read lists, arrays, map collections and objects in yml files?

application.yml defines the array type

yml configuration file is as shown below

dataSync: enable: true type: - "1" - "2" - "3"
Copy after login

Get the array value through @value annotation

@Value("${dataSync.enable.type}")
 private String[] type;
Copy after login

can also be obtained by creating a configuration class bean and using the @ConfigurationProperties annotation , as shown in the following figure:

@Data
@Component
@ConfigurationProperties(prefix = "dataSync.enable") // 配置 文件的前缀
public class InterceptorPathBean
{  
    private String[] type;
}
Copy after login

yml files can also store objects and collections of objects. The usage method is the same as The basic types are similar.
Simple example:

Define map collection configuration

interceptorconfig:
  path:
    maps:
      name: 小明
      age: 24
Copy after login

By creating a configuration class bean, use the @ConfigurationProperties annotation to obtain the map value, as shown in the figure below

@Data
@Component
@ConfigurationProperties(prefix = "interceptorconfig.path") // 配置 文件的前缀
public class InterceptorPathBean
{
    private Map<String , String> maps;
}
Copy after login

Use objects Configuration

student:
  id: 1
  name: Bruce
  gender: male
Copy after login

Use object collection configuration

students: 
  - id: 1
    name: Bruce
    gender: male
  - id: 2
    name: ...
    ...
Copy after login

Here I will summarize some important points for you:

1. In the list type yml configuration file, you need to use "- " to form a collection of lists.

2. There is no level limit for the prefix in yml. If it is multi-level, such as demo/code here, the prefix for configuring the ConfigurationProperties annotation in the java class is written as "demo.code"

3. The attribute name supports the hyphen "-" in the yml file, such as four-span. When configuring the attribute in the java class, it needs to be converted to camel case, fourSpan.

4. Java class attributes need to be configured with set and get methods.

The above is the detailed content of How does springboot read lists, arrays, map collections and objects in yml files?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template