You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring XML配置测试:如何读取application.properties属性?

问题分析与解决方案

你的问题核心是Spring测试上下文未加载属性文件,同时XML配置存在语法错误,以下是具体修正步骤:


1. 修复XML配置的语法错误

你的XML配置开头多了一个无效的</bean>闭合标签,这会导致配置文件解析失败,正确的bean配置应为:

<bean name="myclass" class="com.package.MyClass">
    <property name="userName" value="${username}"/>
    <property name="password" value="${password}"/>
</bean>

2. 在XML中添加属性文件加载配置

Spring不会自动读取application.properties,必须显式配置属性占位符处理器来解析${}格式的占位符。在test.xml中添加以下配置:

<!-- 加载classpath下的application.properties -->
<context:property-placeholder location="classpath:application.properties"/>

若需加载环境特定属性文件(如application-test.properties),可配置多文件优先级加载:

<!-- 优先加载环境专属属性,再加载默认属性 -->
<context:property-placeholder location="classpath:application-${spring.profiles.active:test}.properties,classpath:application.properties"/>

注意:需在XML头部引入context命名空间,否则<context:property-placeholder>会报错,完整头部示例:

<?xml version="1.0" encoding="UTF-8"?>
<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">

3. 修正测试类的语法错误

测试类中@Autowired MyClass缺少变量名,属于语法错误,需补全:

@ExtendWith(SpringExtension.class)
@ContextConfiguration("/test.xml")
public class MyTestClass {

    @Autowired
    private MyClass myClass; // 补全变量名

    // 示例测试方法
    @Test
    void verifyProperties() {
        System.out.println("用户名:" + myClass.getUserName());
        System.out.println("密码:" + myClass.getPassword());
    }
}

4. 确认属性文件路径正确性

确保application.properties放置在src/test/resources目录(测试环境)或src/main/resources目录(主环境),保证Spring能通过classpath:路径找到该文件。


内容的提问来源于stack exchange,提问作者himan01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 12:30:13