【Java Web开发学习】Spring加载外部properties配置文件
【Java Web开发学习】Spring加载外部properties配置文件
转载:https://www.cnblogs.com/yangchongxing/p/9136505.html
1、声明属性源,通过Spring的Environment检索来装配属性
Environment检索的值来源于属性源,直接从Environment中检索属性是非常方便的,尤其在Java配置中装配Bean的时候,。
package com.qq.weixin.mp.config; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; @Configuration @PropertySource(value="classpath:weixin.properties")//属性源,maven配置位于src\main\resources目录下 public class WeixinConfig { private String appid; private String appsecret; @Autowired Environment env; @Bean public Map<String, String> config() { appid = env.getProperty("appid");//检索属性 appsecret = env.getProperty("appsecret");//检索属性 Map<String, String> map = new HashMap<String, String>(); map.put("appid", appid); map.put("appsecret", appsecret); return map; } }
2、有配置类,通过占位符来装配属性
占位符的值来源于属性源,占位符的形式为使用${...}包装的属性名称。
package com.qq.weixin.mp.config; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration @PropertySource(value="classpath:weixin.properties")//属性源 public class WeixinConfig { @Value("${appid}")//占位符 private String appid; @Value("${appsecret}") private String appsecret; @Bean public Map<String, String> config() { Map<String, String> map = new HashMap<String, String>(); map.put("appid", appid); map.put("appsecret", appsecret); return map; } }
或者定义PropertySourcesPlaceholderConfigurer Bean Spring3.1以后推荐使用
@Bean public PropertySourcesPlaceholderConfigurer placeholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); }
<context:property-placeholder />
分类:
00-Java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端