springboot使用工具類無需注入獲取yml配置項


1.新建 BeanConfiguration 類,用於項目啟動構造我們的工具類

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.工具類實現

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.調用示例

String password = YamlConfigurerUtil.getStrYmlVal("redis.password");

 

 

文末小福利免費視頻資源網站:www.sousuohou.com


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM