spring多种方法读取properties配置文件

环境

  • ssm框架
  • jdk1.8
  • IntelliJ IDEA 2019.1.2
  • maven-3.6.1
    项目结构如图
    在这里插入图片描述

方法

我们用三种不同的方法读取config.properties配置文件
第一种方法在spring_mvc.xml编写一下配置

<context:property-placeholder location="classpath:properties/config.properties" ignore-unresolvable="true" file-encoding="GBK"/>

  • ignore-unresolvable=“true” :配置文件 找 不 到 对 应 占 位 符 的 值 不 会 报 错 , 会 直 接 赋 值 ′ {}找不到对应占位符的值 不会报错,会直接赋值&#x27; {}’;如果设为false,会直接报错Could not resolve placeholder ‘key’ in string value${key1}。 设置它为true的主要原因,是一个xml中有多个配置文件时的情况
  • file-encoding=“GBK” 根据自己properties编码格式设置,我的config.properties为GBK

以下配置和上面等效

        <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="ignoreUnresolvablePlaceholders" value="true"/>
            <property name="locations">
                <list>
                    <value>classpath:properties/config.properties</value>
                </list>
            </property>
                 <property name="fileEncoding" value="GBK"/>
        </bean>

注意:你的spring_mvc.xml文件一定要有以下配置

    <!-- 扫描web相关的bean -->
    <context:component-scan base-package="com.demo.controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

第二种方法在spring_mvc.xml编写一下配置

<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <!-- 这里是PropertiesFactoryBean类,它也有个locations属性,也是接收一个数组,跟上面一样 -->
        <property name="locations">
            <array>
                <value>classpath:properties/config.properties</value>
            </array>
        </property>
        <!-- 设置编码格式 -->
        <property name="fileEncoding" value="GBK"></property>
    </bean>

第三种方法编写一个工具类用流读取文件

**
 * 文件获取工具类
 */
public class PropertyUtil {
    private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);
    private static Properties props;

    static {
        loadProps();
    }

    synchronized static private void loadProps() {
        logger.info("开始加载properties文件内容.......");
        props = new Properties();
        InputStream in = null;
        InputStreamReader reader=null;
        try {
            /**
             * 通过类加载器在classPath目录下获取资源.并且是以流的形式
             * getClassLoader()是获取当前的类加载器
             * getResourceAsStream(path)是用来获取资源的
             */
            in = PropertyUtil.class.getClassLoader().getResourceAsStream("properties/config.properties");
            reader = new InputStreamReader(in,"gbk");
            props.load(reader);
        } catch (FileNotFoundException e) {
            logger.error("config.properties文件未找到");
        } catch (IOException e) {
            logger.error("出现IOException");
        } finally {
            try {
                if (null != reader) {
                    reader.close();
                }
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error("jdbc.properties文件流关闭出现异常");
            }
        }
        logger.info("加载properties文件内容完成...........");
        logger.info("properties文件内容:" + props);
    }

    public static String getProperty(String key) {
        if (null == props) {
            loadProps();
        }
        return props.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        if (null == props) {
            loadProps();
        }
        return props.getProperty(key, defaultValue);
    }
}

具体类中应用

@Controller
@RequestMapping("user")
public class UserController {
    Logger logger= LoggerFactory.getLogger(UserController.class);
    //第一种方法获取值
    @Value("${name}")
    private String firstName;
    @Value("${type}")
    private String firstType;
    @Value("${num}")
    private String firstNum;
    //第二种方法获取值
    @Value("#{prop.name}")
    private String twoName;
    @Value("#{prop.type}")
    private String twoType;
    @Value("#{prop.num}")
    private String twoNum;

    /**
     * 第一种方法测试
     * @return
     */
    @RequestMapping("first")
    @ResponseBody
    public Object getProperyFirst()  {
        Map<String,Object> firstResult=new HashMap<>();
        firstResult.put("firstName",firstName);
        firstResult.put("firstType",firstType);
        firstResult.put("firstNum",firstNum);
        return firstResult;
    }

    /**
     * 第2种方法测试
     * @return
     */
    @RequestMapping("two")
    @ResponseBody
    public Object getProperyTwo()  {
        Map<String,Object> twoResult=new HashMap<>();
        twoResult.put("twoName",twoName);
        twoResult.put("twoType",twoType);
        twoResult.put("twoNum",twoNum);
        return twoResult;
    }
    /**
     * 第3种方法测试
     * @return
     */
    @RequestMapping("third")
    @ResponseBody
    public Object getProperyThird( )  {
        String thirdName=PropertyUtil.getProperty("name", "defaultValue");
        String thirdType=PropertyUtil.getProperty("type", "defaultValue");
        String thirdNum=PropertyUtil.getProperty("num", "defaultValue");
        Map<String,Object> twoResult=new HashMap<>();
        twoResult.put("thirdName",thirdName);
        twoResult.put("thirdType",thirdType);
        twoResult.put("thirdNum",thirdNum);
        return twoResult;
    }
}

测试结果

第一种方法结果
在这里插入图片描述
第2种方法结果
在这里插入图片描述
第3种方法结果
在这里插入图片描述
建议用第三种方法。

如果需要了解跟多读取配置文件的方法请点击这儿

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值