1.新建 BeanConfiguration 类,用于项目启动构造我们的工具类
1package webapp.config; 2 3import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; 4import org.springframework.context.annotation.Bean; 5import org.springframework.context.annotation.Configuration; 6import org.springframework.core.io.ClassPathResource; 7import org.springframework.core.io.Resource; 8import webapp.util.YamlConfigurerUtil; 9import java.util.Properties; 10 11@Configuration 12public class BeanConfiguration { 13 @Bean 14 public YamlConfigurerUtil ymlConfigurerUtil() { 15 //1:加载配置文件 16 Resource app = new ClassPathResource("application.yml"); 17 YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean(); 18 // 2:将加载的配置文件交给 YamlPropertiesFactoryBean 19 yamlPropertiesFactoryBean.setResources(app); 20 // 3:将yml转换成 key:val 21 Properties properties = yamlPropertiesFactoryBean.getObject(); 22 // 4: 将Properties 通过构造方法交给我们写的工具类 23 YamlConfigurerUtil ymlConfigurerUtil = new YamlConfigurerUtil(properties); 24 return ymlConfigurerUtil; 25 } 26 27}
2.工具类实现
1package webapp.util; 2 3import java.util.Properties; 4 5public class YamlConfigurerUtil { 6 7 private static Properties ymlProperties = new Properties(); 8 9 public YamlConfigurerUtil(Properties properties){ 10 ymlProperties = properties; 11 } 12 13 public static String getStrYmlVal(String key){ 14 return ymlProperties.getProperty(key); 15 } 16 17 public static Integer getIntegerYmlVal(String key){ 18 return Integer.valueOf(ymlProperties.getProperty(key)); 19 } 20 21}
3.调用示例
1String password = YamlConfigurerUtil.getStrYmlVal("redis.password"); 2 3文末小福利免费视频资源网站:www.sousuohou.com