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

本文详细介绍了在SpringMVC项目中加载Properties配置文件的三种方式:1) 使用`context:property-placeholder`,涉及spring.xml配置、jdbc.properties引用及Java类中的应用;2) 通过`util:properties`加载config.properties,包括配置文件引用和Java类中的使用;3) 直接在Java类中使用注解加载配置文件,并给出了具体示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

         最近开发的项目使用了SpringMVC的框架,用下来感觉SpringMVC的代码实现的非常优雅,功能也非常强大,网上介绍Controller参数绑定、URL映射的文章都很多了,写这篇博客主要总结一下SpringMVC加载配置Properties文件的几种方式

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

  1.1、在spring.xml中加入context相关引用
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd 
http://www.springframework.org/schema/util 
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="mytest" />
<!-- 强制SPRING使用CGLIB动态代理,不使用JDK代理。 -->
<aop:config proxy-target-class="true" />
<!-- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
<property name="locations"> <list> <value>classpath:jdbc.properties</value> 
</list> </property> </bean> -->
    <!--  <context:property-placeholder location="classpath:jdbc.properties" /> -->
<util:properties id="settings" location="classpath:config.properties"/>
</beans>


1.2、引入jdbc配置文件         
<context:property-placeholder location="classpath:jdbc.properties"/>  
1.3、jdbc.properties的配置如下
jdbc_driverClassName=com.mysql.jdbc.Driver  
jdbc_url=jdbc:mysql://localhost/testdb?useUnicode=true&characterEncoding=utf8  
jdbc_username=root  
jdbc_password=123456  
1.4、在Java类中引用jdbc.properties中的配置
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.5、在controller中调用
@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;  
     }   
}  
返回如下结果:
{   
    jdbcUrl:"jdbc:mysql://localhost/testdb?useUnicode=true&characterEncoding=utf8"  
}  
 
注:通过context:property-placeholde加载多个配置文件
 只需在第1.2步中将多个配置文件以逗号分隔即可 
<context:property-placeholder location="classpath:jdbc.properties,classpath:XXX.properties"/>  
 

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

 2.1、在spring.xml中加入util相关引用
<?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配置文件  
<util:properties id="settings" location="classpath:config.properties"/>
2.3、config.properties的配置如下 
gnss.server.url=http://127.0.0.1:8080/gnss/services/data-world/rest  


2.4、在java类中引用config中的配置   
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中调用
@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;  
      }   
}  
返回如下结果:
{  
   "gnss.service.url":"http://127.0.0.1:8080/gnss/services/data-world/rest"  
}  




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

3.1、在java类中引入配置文件
import org.springframework.beans.factory.annotation.Value;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.context.annotation.PropertySource;  
  
@Configuration  
public class Config {   
   
@Value("${gnss.server.url}")   
public  String GNSS_SERVER_URL;  
  
@Value("${gnss.server.url}")   
public  String jdbcUrl;   
  
}  
3.2、在controller中调用
@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、测试
返回如下结果:
{  
   "gnss.service.url":"http://127.0.0.1:8080/gnss/services/data-world/rest"  
 }  
3.4、实例如下:
1)package com.websystique.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import com.websystique.spring.configuration.AppConfig;
import com.websystique.spring.service.FileService;
public class AppMain {
public static void main(String args[]){
AbstractApplicationContext  context = new AnnotationConfigApplicationContext(AppConfig.class);
FileService service = (FileService) context.getBean("fileService");
service.readValues();
context.close();

}


2)package com.websystique.spring.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@ComponentScan(basePackages = "com.websystique.spring")
@PropertySource(value = { "classpath:application.properties" })

public class AppConfig {
/*
* PropertySourcesPlaceHolderConfigurer Bean only required for @Value("{}") annotations.
* Remove this bean if you are not using @Value annotations for injecting properties.
*/
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
}
3)package com.websystique.spring.service;
public interface FileService {
void readValues();
}
4)package com.websystique.spring.service
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
@Service("fileService")
public class FileServiceImpl implements FileService {
@Value("${sourceLocation:c:/temp/input}")
private String source;
@Value("${destinationLocation:c:/temp/output}")
private String destination;
@Autowired
private Environment environment;
public void readValues() {
System.out.println("Getting property via Spring Environment :"
+ environment.getProperty("jdbc.driverClassName"));
System.out.println("Source Location : " + source);
System.out.println("Destination Location : " + destination);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值