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

Maven+Spring项目中如何加载properties文件并实现注入?

嗨,我来帮你搞定这个问题!

解决Spring无XML项目加载properties文件并注入的问题

首先明确一个关键结论:POM.xml不需要添加额外配置。properties文件的加载是Spring的核心功能,和Maven配置无关——只要你的properties文件放在src/main/resources(或其子目录)下,Maven会自动把它打包到项目的类路径中,Spring就能找到它。

接下来给你两种常用的无XML配置方案,以及对应的注入方式:

方案一:加载整个properties文件为Map对象(和旧XML配置效果一致)

如果你需要像之前那样把整个countries.properties封装成Map注入,按以下步骤操作:

  1. 创建Spring配置类,定义加载properties的Bean
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Bean;
import java.util.Properties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.IOException;

@Configuration
@PropertySource("classpath:countries.properties") // 对应resources下的文件路径,子目录要加上,比如classpath:config/countries.properties
public class PropertyConfig {

    // 定义名为countryOptions的Bean,封装整个properties文件内容
    @Bean(name = "countryOptions")
    public Properties countryOptions() throws IOException {
        Resource resource = new ClassPathResource("countries.properties");
        Properties properties = new Properties();
        properties.load(resource.getInputStream());
        return properties;
    }
}
  1. 在业务类中注入Map对象
    因为Properties类实现了Map接口,所以可以直接用你熟悉的@Value("#{countryOptions}")注入:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Map;

@Component
public class YourBusinessClass {

    @Value("#{countryOptions}")
    private Map<String, String> countryOptions;

    // 后续就可以正常使用这个Map了
}

方案二:直接读取单个属性值

如果不需要整个文件的Map,只是读取单个属性,配置会更简洁:

  1. 同样在配置类中添加@PropertySource注解(Spring Boot项目可省略,默认会加载application.properties,自定义文件才需要加):
@Configuration
@PropertySource("classpath:countries.properties")
public class PropertyConfig {
    // 无需额外Bean,Spring会自动处理属性解析
}
  1. 在业务类中用@Value("${属性键}")注入单个值:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class YourBusinessClass {

    // 假设countries.properties里有country.cn=China这样的配置
    @Value("${country.cn}")
    private String chinaCountryName;
}

关键区别说明

  • #{...}是SpEL表达式,用来引用Spring容器中的Bean(比如我们定义的countryOptions)或者执行表达式,适合注入整个Bean/Map对象
  • ${...}是属性占位符,专门用来读取properties文件中的单个键值对,适合注入单个属性值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:28:53