(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中出现的问题,所以多个配置文件中配多个属性文件时还是统一配置吧。。。

  

 

 

  

 

posted @ 2020-04-14 16:54  雷雨客  阅读(1706)  评论(0编辑  收藏  举报