SpringMVC加载配置Properties文件的几种方式

最近开发的项目使用了SpringMVC的框架,用下来感觉SpringMVC的代码实现的非常优雅,功能也非常强大,

网上介绍Controller参数绑定、URL映射的文章都很多了,写这篇博客主要总结一下SpringMVC加载配置Properties文件的几种方式

通过读取Config文件的配置例如:
Map<String, String> group = ConfigurationManager.GetConfiguration("config1");

this.setBcpApi(group.get("BCP.Webapi"));

this.setAppCode(group.get("BCP.AppCode"));

this.setGetCustomerApi(group.get("GetCustomer"));

1.通过context:property-placeholde实现配置文件加载

  1.1、在spring.xml中加入context相关引用

[html] view plain copy
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd">  

 1.2、引入jdbc配置文件         

[html] view plain copy
<context:property-placeholder location="classpath:jdbc.properties"/>
1.3、jdbc.properties的配置如下

[html] view plain copy
jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost/testdb?useUnicode=true&characterEncoding=utf8
jdbc_username=root
jdbc_password=123456  

1.4、在spring-mybatis.xml中引用jdbc中的配置

[html] view plain copy
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
   destroy-method="close" >
   <property name="driverClassName">
     <value>${jdbc_driverClassName}</value>
   </property>
   <property name="url">
     <value>${jdbc_url}</value>
   </property>
   <property name="username">
     <value>${jdbc_username}</value>
   </property>
   <property name="password">
     <value>${jdbc_password}</value>
   </property>
   <!-- 连接池最大使用连接数 -->
   <property name="maxActive">
     <value>20</value>
   </property>
   <!-- 初始化连接大小 -->
   <property name="initialSize">
     <value>1</value>
   </property>
   <!-- 获取连接最大等待时间 -->
   <property name="maxWait">
     <value>60000</value>
   </property>
   <!-- 连接池最大空闲 -->
   <property name="maxIdle">
     <value>20</value>
   </property>
   <!-- 连接池最小空闲 -->
   <property name="minIdle">
     <value>3</value>
   </property>
   <!-- 自动清除无用连接 -->
   <property name="removeAbandoned">
     <value>true</value>
   </property>
   <!-- 清除无用连接的等待时间 -->
   <property name="removeAbandonedTimeout">
     <value>180</value>
   </property>
   <!-- 连接属性 -->
   <property name="connectionProperties">
     <value>clientEncoding=UTF-8</value>
   </property>
 </bean>  

1.5、在java类中引用jdbc.properties中的配置

[html] view plain copy
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;  

@Configuration
public class JdbcConfig{      

    @Value("${jdbc_url}")
    public  String jdbcUrl; //这里变量不能定义成static  

    @Value("${jdbc_username}")
    public  String username;    

    @Value("${jdbc_password}")
    public  String password;    

}  

1.6、在controller中调用

[html] view plain copy
@RequestMapping("/service/**")
@Controller
public class JdbcController{  

         @Autowired
     private JdbcConfig Config; //引用统一的参数配置类  

         @Value("${jdbc_url}")
         private String jdbcUrl; //直接在Controller引用
         @RequestMapping(value={"/test"})
        public ModelMap test(ModelMap modelMap) {
               modelMap.put("jdbcUrl", Config.jdbcUrl);
               return modelMap;
          }
         @RequestMapping(value={"/test2"})
     public ModelMap test2(ModelMap modelMap) {
           modelMap.put("jdbcUrl", this.jdbcUrl);
           return modelMap;
     }
}  

1.7、测试

在ie中输入http://localhost:8080/testWeb/service/test 或http://localhost:8080/testWeb/service/test2  

返回如下结果:

[java] view plain copy
{
    jdbcUrl:"jdbc:mysql://localhost/testdb?useUnicode=true&characterEncoding=utf8"
}  

注:通过context:property-placeholde加载多个配置文件

 只需在第1.2步中将多个配置文件以逗号分隔即可 

[html] view plain copy
<context:property-placeholder location="classpath:jdbc.properties,classpath:XXX.properties"/>  

2、通过util:properties实现配置文件加载

 2.1、在spring.xml中加入util相关引用

[html] view plain copy
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:util="http://www.springframework.org/schema/util"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/util
      http://www.springframework.org/schema/util/spring-util-4.0.xsd">
2.2、 引入config配置文件  

[html] view plain copy
<util:properties id="settings" location="classpath:config.properties"/>  

2.3、config.properties的配置如下 

[html] view plain copy
gnss.server.url=http://127.0.0.1:8080/gnss/services/data-world/rest  

2.4、在java类中引用config中的配置
[html] view plain copy
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;  

@Component
public class Config {
      @Value("#{settings[‘gnss.server.url‘]}")
      public  String GNSS_SERVER_URL;   

}
2.5、在controller中调用

[html] view plain copy
@RequestMapping("/service2/**")
@Controller
public class ConfigController{  

         @Autowired
     private Config Config; //引用统一的参数配置类  

         @RequestMapping(value={"/test"})
     public ModelMap test(ModelMap modelMap) {
        modelMap.put("gnss.service.url",Config.GNSS_SERVER_URL);
            return modelMap;
      }
}  

2.6、测试

在ie中输入http://localhost:8080/testWeb/service2/test

返回如下结果:

[html] view plain copy
{
   "gnss.service.url":"http://127.0.0.1:8080/gnss/services/data-world/rest"
}  

3.直接在Java类中通过注解实现配置文件加载

3.1、在java类中引入配置文件

[java] view plain copy
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;  

@Configuration
@PropertySource(value="classpath:config.properties")
public class Config {   

@Value("${gnss.server.url}")
public  String GNSS_SERVER_URL;  

@Value("${gnss.server.url}")
public  String jdbcUrl;   

}
3.2、在controller中调用
[java] view plain copy
@RequestMapping("/service2/**")
@Controller
public class ConfigController{  

         @Autowired
     private Config Config; //引用统一的参数配置类  

          @RequestMapping(value={"/test"})
     public ModelMap test(ModelMap modelMap) {
        modelMap.put("gnss.service.url", Config.GNSS_SERVER_URL);
            return modelMap;
     }
}
3.3、测试

在ie中输入http://localhost:8080/testWeb/service2/test

返回如下结果:

[java] view plain copy
{
   "gnss.service.url":"http://127.0.0.1:8080/gnss/services/data-world/rest"
 }  

最后附上spring.xml的完整配置:

[html] view plain copy
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:util="http://www.springframework.org/schema/util"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/util
      http://www.springframework.org/schema/util/spring-util-4.0.xsd">  

    <!-- 引入jdbc配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>  

     <!-- 引入多配置文件 -->
       <context:property-placeholder location="classpath:jdbc.properties,classpath:XXX.properties"/>
     <!-- 通过util引入config配置文件 -->
     <!-- <util:properties id="settings" location="classpath:config.properties" /> -->
     <!-- 扫描文件(自动将servicec层注入) -->
     <context:component-scan base-package="修改成你的Config类所在的package"/></beans>
个人分类: java web

  

原文地址:https://www.cnblogs.com/xiaofengfeng/p/9174482.html

时间: 2024-08-04 23:10:00

SpringMVC加载配置Properties文件的几种方式的相关文章

spring加载hibernate映射文件的几种方式。转自:http://blog.csdn.net/huiwenjie168/article/details/7013618

在Spring的applicationContext.xml中配置映射文件,通常是在<sessionFactory>这个Bean实例中进行的,若配置的映射文件较少时,可以用sessionFactory的所属类LocalSessionFactoryBean的“mappingResources”属性,方式包括(mappingResources,mappingLocations.mappingDirectoryLocations与mappingJarLocations )定义方法如下: 第一种: &

spring加载hibernate映射文件的几种方式 (转)

在Spring的applicationContext.xml中配置映射文件,通常是在<sessionFactory>这个 Bean实例中进行的,若配置的映射文件较少时,可以用sessionFactory的所属类LocalSessionFactoryBean的 “mappingResources”属性,方式包括(mappingResources,mappingLocations. mappingDirectoryLocations与mappingJarLocations )定义方法如下: 第一种

Spring加载properties文件的两种方式

在项目中如果有些参数经常需要修改,或者后期可能需要修改,那我们最好把这些参数放到properties文件中,源代码中读取properties里面的配置,这样后期只需要改动properties文件即可,不需要修改源代码,这样更加方便.在Spring中也可以这么做,而且Spring有两种加载properties文件的方式:基于xml方式和基于注解方式.下面分别讨论下这两种方式. 1. 通过xml方式加载properties文件 我们以Spring实例化dataSource为例,我们一般会在beans

Java实现动态加载读取properties文件

问题: 当我们使用如下语句加载.properties时: ClassLoader classLoader = this.getClass().getClassLoader(); Properties prop = new Properties(); prop.load(classLoader.getResourceAsStream("/Application.properties")); 会发现修改了.properties后,即使重新执行,读入的仍为修改前的参数.此问题的原因在于Cla

解密Spring加载的Properties文件

Spring的框架中,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer类可以将.properties(key/value形式)文件中 一些动态设定的值(value),在XML中替换为占位该键($key$)的值, .properties文件可以根据客户需求,自定义一些相关的参数,这样的设计可提供程序的灵活性. xml中的配置文件 <bean id="propertyConfigurer" c

加载gif动态图的三种方式

准备:本地图片资源,GifView GifView代码: /** * 调用结束就开始播放动画,如果需要用户指定何时播放的话,只需要把timer的开始放到合适的位置.通过对CFDictonaryRaf 也就是gifProperties的改变,我们还可以控制动画是否循环播放以及循环多少次停止. 通过对index的改变也可以控制动画从某帧开始播放.同理,同时改变index和count的话,也可以控制从某帧到某帧的播放. 注意:- (void)stopGif;之后才可以退出这个类.否则timer不会关闭

js中页面加载完成后执行的几种方式及执行顺序

在js和jquery使用中,经常使用到页面加载完成后执行某一方法.通过整理,大概是五种方式(其中有的只是书写方式不一样). 1:使用jQuery的$(function){}; 2:使用jquery的$(document).ready(function(){});前两者本质上没有区别,第1种是第2种的简写方式.两个是document加载完成后就执行方法. 3:使用jQuery的$(window).load(function(){}); 4:使用window.onload = function(){

spring加载配置属性文件(properties)

两种方法: -----------------------------------1---------------------------- <!-- 加载链接数据库属性文件 --> <context:property-placeholder location="classpath:dataSource-configer.properties" /> -----------------------------------2--------------------

java web项目启动时自动加载自定义properties文件

首先创建一个类 public class ContextInitListener implements ServletContextListener 使得该类成为一个监听器.用于监听整个容器生命周期的,主要是初始化和销毁的. 类创建后要在web.xml配置文件中增加一个简单的监听器配置,即刚才我们定义的类. Xml代码 <listener> <!-- lang: xml --> <description>ServletContextListener</descri