关于如何读取yml

大概有两种方式

1、使用@Value方式,下面是static方式,正常使用的话直接@Value加在成员变量上

package com.tf.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class RedisConfig {
	private static String company;
	private static String project;
	private static String version;
	
	@Value("${redis.key.companyname}")
	public void setCompany(String company) {
		RedisConfig.company = company;
	}
	@Value("${redis.key.projectname}")
	public void setProject(String project) {
		RedisConfig.project = project;
	}
	@Value("${redis.key.version}")
	public void setVersion(String version) {
		RedisConfig.version = version;
	}
	public static String getCompany() {
		return company;
	}
	public static String getProject() {
		return project;
	}
	public static String getVersion() {
		return version;
	}
}

2、使用snakeyaml直接解析、需要添加如下依赖

<dependency>
	<groupId>org.yaml</groupId>
	<artifactId>snakeyaml</artifactId>
</dependency>
import java.io.IOException;
import java.util.Map;

import org.springframework.core.io.ClassPathResource;
import org.yaml.snakeyaml.Yaml;

public class YamlUtil {
	public static Object getValueMap(String key){
		Yaml yaml = new Yaml();
		Object result = null;
		try {
			String env = System.getenv("env") != null ? System.getenv("env") : "dev";
			ClassPathResource classPathResource = new ClassPathResource("application-" + env + ".yml");
			Map<String, Object> map = yaml.load(classPathResource.getInputStream());
			result = map.get(key);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return result;
	}
}
  • 调用
import java.util.Map;

public class RedisUtil {
	private static Map<String, Map<String, String>> makeKey = (Map<String, Map<String, String>>) YamlUtils.getValueMap("redis");
	private static String company = makeKey.get("key").get("companyname");
	private static String project = makeKey.get("key").get("projectname");
	private static String version = makeKey.get("key").get("version");
	
	public static String makeKey(String key){
		if(version != null && !"".equals(version)){
			return company + ":" + project + ":" +version + ":" + key;
		}else{
			return company + ":" + project + ":" + key;
		}
	}
}