首页 > 编程语言 > 详细

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

时间:2020-04-14 17:57:45      阅读:66      评论:0      收藏:0      [点我收藏+]

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

  

 

 

  

 

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

原文:https://www.cnblogs.com/javasl/p/12699015.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!