1.新建 BeanConfiguration 類,用於項目啓動構造咱們的工具類java
package webapp.config; import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import webapp.util.YamlConfigurerUtil; import java.util.Properties; @Configuration public class BeanConfiguration { @Bean public YamlConfigurerUtil ymlConfigurerUtil() { //1:加載配置文件 Resource app = new ClassPathResource("application.yml"); YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean(); // 2:將加載的配置文件交給 YamlPropertiesFactoryBean yamlPropertiesFactoryBean.setResources(app); // 3:將yml轉換成 key:val Properties properties = yamlPropertiesFactoryBean.getObject(); // 4: 將Properties 經過構造方法交給咱們寫的工具類 YamlConfigurerUtil ymlConfigurerUtil = new YamlConfigurerUtil(properties); return ymlConfigurerUtil; } }
2.工具類實現web
package webapp.util; import java.util.Properties; public class YamlConfigurerUtil { private static Properties ymlProperties = new Properties(); public YamlConfigurerUtil(Properties properties){ ymlProperties = properties; } public static String getStrYmlVal(String key){ return ymlProperties.getProperty(key); } public static Integer getIntegerYmlVal(String key){ return Integer.valueOf(ymlProperties.getProperty(key)); } }
3.調用示例redis
String password = YamlConfigurerUtil.getStrYmlVal("redis.password");
文末小福利免費視頻資源網站:www.sousuohou.com