springboot获取配置文件中的信息

1.加载PropertiesFactoryBean

import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;

/**
 * @author lance
 * @describe 设置properties编码格式
 **/
@Configuration
public class PropertiesConfig
{
    @Bean
    public PropertiesFactoryBean getPropertiesFactoryBean() throws IOException
    {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("config/application.properties"));
        propertiesFactoryBean.setFileEncoding("UTF-8");
        return propertiesFactoryBean;
    }
}

2.启动时加载properties信息

import com.lance.api.common.util.ResourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author lance
 * @describe 启动时加载properties信息
 **/
@Component
@Order(value = 1)
public class InitLoading implements CommandLineRunner
{
    @Autowired
    PropertiesConfig propertiesConfig;

    @Override
    public void run(String... args) throws Exception
    {
        // 加载配置文件信息
        ResourceUtil.ctxProperties = propertiesConfig.getPropertiesFactoryBean().getObject();
    }
}

工具类

import org.springframework.util.StringUtils;

import java.util.Properties;


/**
 * @author lance
 * @describe 系统资源工具类
 **/
public class ResourceUtil
{
    public static Properties ctxProperties;

    private ResourceUtil()
    {
    }

    /**
     * 取值
     *
     * @param key
     * @return
     */
    public static String getValue(String key)
    {
        return ctxProperties.getProperty(key);
    }

    /**
     * 取值
     *
     * @param key
     * @param defaultVal
     * @return
     */
    public static String getValue(String key, String defaultVal)
    {
        String value = ctxProperties.getProperty(key);
        return StringUtils.isEmpty(value) ? defaultVal : value;
    }
}

猜你喜欢

转载自blog.csdn.net/sinat_30637097/article/details/87006495