要将Map写入YAML文件中,您可以将Map转换为YAML格式的字符串,然后将其写入YAML文件。然后,您可以使用@Value注解将YAML文件中的值注入到Spring应用程序的字段或方法中。

以下是一个示例:

首先,将Map转换为YAML格式的字符串:

import org.yaml.snakeyaml.Yaml;

Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");

Yaml yaml = new Yaml();
String yamlString = yaml.dump(map);

接下来,将YAML字符串写入YAML文件:

import java.io.FileWriter;
import java.io.IOException;

try {
    FileWriter writer = new FileWriter("config.yml");
    writer.write(yamlString);
    writer.close();
} catch (IOException e) {
    e.printStackTrace();
}

现在,您可以在YAML文件中使用@Value注解将值注入到Spring应用程序中:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    
    @Value("${key1}")
    private String value1;
    
    @Value("${key2}")
    private String value2;
    
    // Getter and setter methods
    
    // ...
}

在上面的示例中,@Value注解使用${key}的形式来获取YAML文件中的值。在这种情况下,value1将被注入为"value1",value2将被注入为"value2"。

请确保在Spring应用程序的配置文件中包含以下内容,以使@Value注解能够解析YAML文件中的值:

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:config.yml")
public class AppConfig {
    
    // ...
}

上面的示例假设您的配置文件名为"config.yml",并且位于src/main/resources目录下。如果您的配置文件位于其他位置,请相应地更改@PropertySource注解中的路径

java怎么把map写到yml里面然后使用Value注解取出来

原文地址: https://www.cveoy.top/t/topic/hIau 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录