• (03)Spring MVC之读取properties属性文件


      利用Spring读取properties属性文件有很多种方法,这里介绍一种

      (1)在spring-context.xml或者spring-mvc.xml等配置文件中配置context:property-placeholder

      (2)配置文件中读取用$大括号,如:${maxUploadSize}

      (3)java文件中读取用Value注解。

      演示:

      common.properties,配置文件1

    url=192.168.1.1
    message=hello
    #10M
    maxUploadSize=10485760

      common2.properties,配置文件2,url、message属性重复,后面演示怎样取值的

    url=192.168.1.10
    message=hello2
    port=1234

      spring-context.xml,配置了两个属性文件,以逗号分隔

    <context:property-placeholder location="classpath:common.properties,
                                            classpath:common2.properties"/>

      spring-mvc.xml,虽然spring-context.xml中已经配置了,但是spring-mvc.xml中使用还要配置,读取用${maxUploadSize}

    <context:property-placeholder location="classpath:common.properties,
                                            classpath:common2.properties"/>
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--上传文件的最大值,单位为字节 --> <property name="maxUploadSize" value="${maxUploadSize}"/> <!-- 上传文件的编码 --> <property name="defaultEncoding" value="UTF-8"/> </bean>

      TestController.java

    package com.sl.controller;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    @RequestMapping("/test")
    public class TestController {
        
        @Value("${url}")
        private String url;
        
        @Value("${message}")
        private String message;
        
        @Value("${port}")
        private String port;
        
        @Value("${maxUploadSize}")
        private String maxUploadSize;
        
        @RequestMapping("/getProperty")
        @ResponseBody
        public String getProperty() {
            System.out.println("------------------------------------------------------");
            System.out.println("url:"+url);
            System.out.println("message:"+message);
            System.out.println("port:"+port);
            System.out.println("maxUploadSize:"+maxUploadSize);
            System.out.println("------------------------------------------------------");
            return "asasasas";
        }
    }

      运行结果:

      (a)重复的属性读取的是common2.properties中的,common2.properties是配置在后面的,猜测属性重复按照后面的吧。

      (b)如果spring-context.xml中配置了两个属性文件,spring-mvc.xml中配置了一个属性文件,可能启动报错,我遇到了。

      (c)基于上面b中出现的问题,所以多个配置文件中配多个属性文件时还是统一配置吧。。。

      

      

  • 相关阅读:
    超级详细Tcpdump 的用法
    Javascript网站繁简转换解决方案
    IIS6.0下创建用户隔离模式FTP站点
    如何开启IIS里的FTP主动模式(PASV模式)
    C#正则表达式小结
    ServU权限提升再提升记一次虚拟主机入侵
    Linux命令网络操作之ifconfig
    创建使用 Active Directory 模式隔离用户的新 FTP 站点
    远程控制电脑创建影子帐户(后门)
    Linux shell编程笔记总结
  • 原文地址:https://www.cnblogs.com/javasl/p/12699015.html
Copyright © 2020-2023  润新知