Spring读取类路径配置文件返回null的原因与解决方法
核心原因分析
配置文件路径不匹配
你的person.properties位于v4.c3.property包下,对应类路径的正确路径是classpath:v4/c3/property/person.properties。如果@PropertySource中写的是person.properties或其他错误路径,Spring会找不到文件,自然返回null。Maven未打包该配置文件
默认情况下,Maven仅会将src/main/resources目录下的文件打包到classpath中。你把配置文件放在了src/main/java下的包内,若pom.xml未配置资源过滤规则,这个文件不会被加入到最终的classpath,导致Spring无法读取。配置类或测试类注解缺失
- 若Config类未添加
@Configuration注解,Spring不会将其识别为配置类,属性源无法被加载。 - 测试类若未指定加载Config类(比如没加
@ContextConfiguration或@SpringJUnitConfig),Spring容器初始化时不会加载对应的配置,Environment也就读不到属性。
- 若Config类未添加
不必要的PropertySourcesPlaceholderConfigurer Bean
你声明的静态PropertySourcesPlaceholderConfigurer主要用于解析@Value中的占位符,而你用的是Environment读取属性,这个Bean不仅多余,若配置有误还可能干扰属性源的正常加载。
正确实现步骤
1. 修正@PropertySource路径
在配置类或测试类上指定正确的类路径:
@PropertySource("classpath:v4/c3/property/person.properties")
建议将@PropertySource直接加在Config类上,统一管理配置。
2. 配置Maven资源过滤(针对src/main/java下的配置文件)
在pom.xml中添加资源配置,确保src/main/java下的properties文件被打包:
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
如果后续把配置文件移到src/main/resources下的对应目录,可省略这一步。
3. 完善配置类与测试类
- Config类添加
@Configuration注解,可移除不必要的PropertySourcesPlaceholderConfigurer:
@Configuration @PropertySource("classpath:v4/c3/property/person.properties") public class Config { // 若不需要用@Value解析占位符,删除下面的Bean // public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { // return new PropertySourcesPlaceholderConfigurer(); // } }
- 测试类使用
@SpringJUnitConfig加载配置类并注入Environment:
@SpringJUnitConfig(classes = Config.class) public class PropertyTest { @Autowired private Environment env; @Test public void testReadName() { String name = env.getProperty("name"); System.out.println("The name is:" + name); } }
4. 验证打包结果
执行mvn clean package后,检查target/classes/v4/c3/property/目录下是否存在person.properties,确认文件已被正确打包。
内容的提问来源于stack exchange,提问作者vlddlv4

