0.要读取的配置文件
server: port: 8999 hc: test1: test1111 test2: test2222
1.通过Environment读取
@Autowired
private Environment env;
@RequestMapping("/read1")
public String readYml1(int i) {
String property = env.getProperty("hc.test"+i);
return property;
}
2.封装相关工具类
@RequestMapping("/read")
public String readYml(int i) {
String property = EnvironmentUtil.getProperty("hc.test"+i);
return property;
}
import org.springframework.core.env.Environment;
public class EnvironmentUtil {
public static Environment environment = SpringUtil.getBean(Environment.class);
public static String getProperty(String key) {
return environment.getProperty(key);
}
}
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
@Component
public final class SpringUtil implements BeanFactoryPostProcessor {
private static ConfigurableListableBeanFactory beanFactory;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
SpringUtil.beanFactory = beanFactory;
}
public static T getBean(Class clz) throws BeansException {
T result = (T) beanFactory.getBean(clz);
return result;
}
}



