springmvc中如何从配置文件中读取信息

本文介绍了一种不依赖数据库,而通过配置文件实现用户登录验证的方法。主要包括创建.properties文件存放用户名密码、使用Spring MVC配置文件加载这些信息,并创建JavaBean进行管理。

在开发过程中,有的时候系统并不需要从数据库中读取用户登录信息,而是简单的写在一个配置文件中,从配置文件中验证用户名、密码。具体思路如下:

 

1、第一步,先新建一个.properties文件,该文件主要定义系统初始化的用户名、密码

app.properties 写道
admin=admin
test=test

 

2、第二步,新建一个xml文件,主要作用是在springmvc中定义一个bean对象

 <!-- 系统配置参数. -->    
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">    
        <!-- 多个PropertyPlaceholderConfigurer,需要设置本属性为true. -->
        <property name="ignoreUnresolvablePlaceholders" value="true" />        
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />        
        <property name="location" value="classpath:/fynetAdminSettings/app.properties" />    
    </bean>
    
    <bean id="sysUsersConfigBean" class="com.fyard.fynet.core.settings.admin.SysUsersConfigBean">    
        <property name="sysUserInfo">       
            <map>         
                <entry key="admin">            
                    <value>${admin}</value>         
                </entry>
                <entry key="test">            
                    <value>${test}</value>         
                </entry>              
            </map>    
        </property>    
    </bean>

 

 

3、第三步,新建一个JAVABEAN对象,xml文件中的class属性值就是该javabean的具体位置,property值就是javabean中的字段,具体代码如下:

 

package com.fyard.fynet.core.settings.admin;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Component;

/**
 * 系统用户对象
 * 
 */
@Component
public class SysUsersConfigBean {
    private Map<String, String> sysUserInfo = new HashMap<String, String>();

    public Map<String, String> getSysUserInfo() {
        return sysUserInfo;
    }

    public void setSysUserInfo(Map<String, String> sysUserInfo) {
        this.sysUserInfo = sysUserInfo;
    }

    public String getPassword(String username) {
        return sysUserInfo.get(username);
    }
}

以上三步就可以直接读取配置文件中的数据,.properties文件中的值会自动映射到xml文件中的bean中,SysUsersConfigBean该类已经被标注为@Component,在service层就可以直接调用即可

 

<think>我们正在讨论Spring MVC中读取properties文件的配置方法。根据用户提供的引用内容,我们可以总结几种常见的配置方式。下面将详细介绍这些方法,并给出示例代码和配置。 ### 方法一:使用`<context:property-placeholder>`(推荐用于占位符替换) 这是最常用的方式,特别适合在XML配置中使用`${}`占位符注入属性值。 **配置示例**: ```xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 加载单个properties文件 --> <context:property-placeholder location="classpath:config.properties" ignore-unresolvable="true" file-encoding="UTF-8"/> <!-- 加载多个properties文件 --> <context:property-placeholder location="classpath:config.properties, classpath:db.properties" ignore-unresolvable="true" file-encoding="UTF-8"/> <!-- 使用占位符注入属性 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> </beans> ``` **参数说明**: - `location`:指定properties文件的位置,多个文件用逗号分隔。 - `ignore-unresolvable`:设置为`true`时,如果找不到对应的占位符不会报错,而是保留原字符串(如`${unknown}`);设置为`false`则会抛出异常。默认为`false`。 - `file-encoding`:指定properties文件的编码,如UTF-8、GBK等。 **注意**:在同一个Spring配置文件中,只能有一个`<context:property-placeholder>`,如果需要加载多个文件,可以在`location`中使用逗号分隔。如果需要多个`PropertyPlaceholderConfigurer`,请使用方法二。 ### 方法二:使用`PropertyPlaceholderConfigurer` Bean(更灵活) 这种方式可以配置多个`PropertyPlaceholderConfigurer`,并且支持更复杂的设置。 **配置示例**: ```xml <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:config.properties</value> <value>classpath:db.properties</value> <!-- 也可以加载外部文件 --> <value>file:/path/to/external/config.properties</value> </list> </property> <property name="ignoreUnresolvablePlaceholders" value="true"/> <property name="fileEncoding" value="UTF-8"/> </bean> ``` **参数说明**: - `locations`:指定properties文件的位置列表,可以是`classpath:`(类路径下)或`file:`(文件系统绝对路径)。 - `ignoreUnresolvablePlaceholders`:同方法一的`ignore-unresolvable`。 - `fileEncoding`:文件编码。 ### 方法三:使用`PropertiesFactoryBean`(获取Properties对象) 如果我们需要将properties文件加载为一个`java.util.Properties`对象,并注入到其他Bean中,可以使用这种方式。 **配置示例**: ```xml <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath:config.properties</value> </list> </property> <property name="fileEncoding" value="UTF-8"/> </bean> <!-- 使用Properties对象 --> <bean id="someBean" class="com.example.SomeBean"> <property name="properties" ref="configProperties"/> </bean> ``` 在Java代码中,我们可以这样使用: ```java public class SomeBean { private Properties properties; public void setProperties(Properties properties) { this.properties = properties; } public void doSomething() { String value = properties.getProperty("key"); // ... } } ``` ### 方法四:注解方式(结合Spring MVC) 在Spring MVC中,我们通常也会使用注解配置。可以在Java配置类中结合`@PropertySource`和`@Value`。 **配置示例**: ```java @Configuration @PropertySource("classpath:config.properties") public class AppConfig { @Value("${jdbc.url}") private String jdbcUrl; // 如果属性不存在,可以设置默认值 @Value("${jdbc.timeout:3000}") private int timeout; @Bean public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setUrl(jdbcUrl); // ... return dataSource; } } ``` **注意**:使用`@PropertySource`需要配合`PropertySourcesPlaceholderConfigurer`,在Java配置中,我们可以这样配置: ```java @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } ``` ### 总结 在Spring MVC中读取properties文件,主要有以下几种方式: 1. **XML占位符替换**:使用`<context:property-placeholder>`或`PropertyPlaceholderConfigurer`,适合在XML配置中使用`${}`占位符。 2. **加载为Properties对象**:使用`PropertiesFactoryBean`,适合需要直接操作Properties对象的场景。 3. **注解方式**:使用`@PropertySource`和`@Value`,适合基于Java配置的项目。 **最佳实践建议**: - 对于简单的键值注入,推荐使用`<context:property-placeholder>`。 - 需要加载外部配置文件时,可以使用`file:`路径。 - 注意文件编码,避免中文乱码。 - 使用`ignore-unresolvable="true"`可以避免因某些配置缺失导致整个容器启动失败。 ### 常见问题 **Q1:如何加载多个properties文件?** - 在`<context:property-placeholder>`的`location`属性中用逗号分隔多个文件路径。 - 在`PropertyPlaceholderConfigurer`的`locations`属性中使用`<list>`包含多个`<value>`。 **Q2:如何解决中文乱码问题?** - 确保properties文件保存为UTF-8编码(推荐)。 - 在配置中指定`file-encoding="UTF-8"`(或相应编码)。 **Q3:如何引用其他XML文件中定义的占位符?** - 确保在Spring容器中只有一个`PropertyPlaceholderConfigurer`(或`<context:property-placeholder>`),因为Spring不允许覆盖。 - 或者将多个XML文件的占位符配置合并到一个文件中。 §§相关问题§§ 1. 在Spring MVC中如何实现多环境(如dev, test, prod)的properties文件配置? 2. 如何在Spring中安全地管理数据库密码等敏感配置信息? 3. Spring Boot中读取properties文件与Spring MVC有何不同?</think>### Spring MVC 读取 Properties 文件的配置方法 在 Spring MVC 中读取 properties 文件主要有以下几种配置方式,根据您的需求选择合适的方法: #### 方法一:使用 `<context:property-placeholder>`(最常用) ```xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 加载单个properties文件 --> <context:property-placeholder location="classpath:config.properties" ignore-unresolvable="true" file-encoding="UTF-8"/> <!-- 加载多个properties文件 --> <context:property-placeholder location="classpath:config.properties, classpath:db.properties" ignore-unresolvable="true" file-encoding="UTF-8"/> <!-- 使用占位符注入属性 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> </beans> ``` **关键参数说明**: - `location`:配置文件路径(`classpath:`表示资源目录) - `ignore-unresolvable`:设为`true`时找不到占位符不报错[^1] - `file-encoding`:指定文件编码(如UTF-8、GBK等)[^1] #### 方法二:使用 `PropertyPlaceholderConfigurer` Bean ```xml <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <!-- 加载类路径下的文件 --> <value>classpath:config.properties</value> <!-- 加载外部绝对路径文件 --> <value>file:/etc/app/config.properties</value> </list> </property> <property name="ignoreUnresolvablePlaceholders" value="true"/> <property name="fileEncoding" value="UTF-8"/> </bean> ``` **优势**:支持同时加载类路径和文件系统路径的配置文件[^4] #### 方法三:使用 `PropertiesFactoryBean`(获取Properties对象) ```xml <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath:config.properties</value> </list> </property> <property name="fileEncoding" value="UTF-8"/> </bean> <!-- 注入Properties对象 --> <bean id="serviceBean" class="com.example.MyService"> <property name="config" ref="configProperties"/> </bean> ``` **使用场景**:当需要直接操作Properties对象而非占位符替换时[^3] #### 方法四:注解方式(需开启组件扫描) ```java @Configuration @PropertySource("classpath:config.properties") public class AppConfig { @Value("${app.name}") private String appName; @Autowired private Environment env; // 通过环境对象获取 public String getDbUrl() { return env.getProperty("db.url"); } } ``` **XML配置支持**: ```xml <context:component-scan base-package="com.example.config"/> ``` ### 最佳实践建议 1. **路径规范**: - 开发环境:`classpath:config.properties` - 生产环境:`file:/path/to/external/config.properties`[^4] 2. **编码处理**: ```xml <!-- 明确指定中文字符集 --> <property name="fileEncoding" value="UTF-8"/> ``` 3. **多文件加载**: ```xml <property name="locations"> <list> <value>classpath:base.properties</value> <value>classpath:${spring.profiles.active}.properties</value> </list> </property> ``` 4. **错误处理**: - 设置`ignore-unresolvable="true"`避免因缺失属性导致启动失败[^1] - 使用默认值:`@Value("${timeout:30}")` ### 配置优先级总结 | 方法 | 适用场景 | 优势 | |------|----------|------| | `<context:property-placeholder>` | 占位符替换 | 简洁易用 | | `PropertyPlaceholderConfigurer` | 复杂路径需求 | 支持外部文件 | | `PropertiesFactoryBean` | 需Properties对象 | 直接操作配置 | | `@PropertySource` | 注解驱动项目 | 类型安全 | > 提示:Spring Boot中推荐使用`@ConfigurationProperties`,但在传统Spring MVC项目中以上XML配置仍是主流方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值