要将Map写入YAML文件中,您可以将Map转换为YAML格式的字符串,然后将其写入YAML文件。然后,您可以使用@Value注解将YAML文件中的值注入到Spring应用程序的字段或方法中。\n\n以下是一个示例:\n\n首先,将Map转换为YAML格式的字符串:\n\njava\nimport org.yaml.snakeyaml.Yaml;\n\nMap<String, String> map = new HashMap<>();\nmap.put("key1", "value1");\nmap.put("key2", "value2");\n\nYaml yaml = new Yaml();\nString yamlString = yaml.dump(map);\n\n\n接下来,将YAML字符串写入YAML文件:\n\njava\nimport java.io.FileWriter;\nimport java.io.IOException;\n\ntry {\n FileWriter writer = new FileWriter("config.yml");\n writer.write(yamlString);\n writer.close();\n} catch (IOException e) {\n e.printStackTrace();\n}\n\n\n现在,您可以在YAML文件中使用@Value注解将值注入到Spring应用程序中:\n\njava\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Configuration;\n\n@Configuration\npublic class AppConfig {\n \n @Value("${key1}")\n private String value1;\n \n @Value("${key2}")\n private String value2;\n \n // Getter and setter methods\n \n // ...\n}\n\n\n在上面的示例中,@Value注解使用${key}的形式来获取YAML文件中的值。在这种情况下,value1将被注入为"value1",value2将被注入为"value2"。\n\n请确保在Spring应用程序的配置文件中包含以下内容,以使@Value注解能够解析YAML文件中的值:\n\njava\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.PropertySource;\n\n@Configuration\n@PropertySource("classpath:config.yml")\npublic class AppConfig {\n \n // ...\n}\n\n\n上面的示例假设您的配置文件名为"config.yml",并且位于src/main/resources目录下。如果您的配置文件位于其他位置,请相应地更改@PropertySource注解中的路径。


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

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