@PropertySource的使用

假设我们有一个名为 database.properties 的属性文件,内容如下,该文件位于项目的类路径 (resources 目录) 下:

java 复制代码
# database.properties
db.url=jdbc:mysql://localhost:3306/mydb
db.username=root
db.password=password

然后,创建一个 Spring 配置类,使用 @PropertySource 加载上述属性文件,并在配置类中使用这些属性:

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:database.properties") // 加载属性文件
public class AppConfig {

    @Autowired
    private Environment env; // 注入环境变量,以便访问属性

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        // 从环境变量中读取属性并设置到数据源中
        dataSource.setUrl(env.getProperty("db.url"));
        dataSource.setUsername(env.getProperty("db.username"));
        dataSource.setPassword(env.getProperty("db.password"));

        return dataSource;
    }
}

我们可以通过 @PropertySource 注解指定了 database.properties 文件的位置。然后,使用 @Autowired 注入 Environment 对象,通过调用 env.getProperty() 方法读取属性值,并将这些值应用于数据源 (DataSource) 的配置中。这样,当 Spring 应用启动时,它会自动读取这些外部配置,并正确地配置数据源 Bean,无需硬编码任何数据库连接细节。

相关推荐
梦里不知身是客1129 分钟前
kettle的mysql 根据条件,导出到不同的excel中
数据库·mysql·excel
sanggou39 分钟前
踩坑记录:PDManer 导出 Oracle DDL 默认值成 ‘NULL‘ 字符串的排查与解决
数据库·oracle
动亦定41 分钟前
MySQL 锁等待超时错误。详细解释原因和解决方案
数据库·mysql
数据库学啊1 小时前
分布式数据库架构设计指南:TDengine如何支持10亿级数据点的水平扩展
数据库·分布式·时序数据库·数据库架构·tdengine
郝学胜-神的一滴1 小时前
Qt删除布局与布局切换技术详解
开发语言·数据库·c++·qt·程序人生·系统架构
小丁爱养花2 小时前
Redis - set & zset (常用命令/内部编码/应用场景)
数据库·redis·缓存
GottdesKrieges3 小时前
OceanBase集群诊断工具:obdiag
数据库·sql·oceanbase
大G的笔记本3 小时前
用 Redis 的 List 存储库存队列,并通过 LPOP 原子性出队来保证并发安全案例
java·数据库·redis·缓存
流子4 小时前
etcd安装与配置完全指南
数据库·etcd
涔溪4 小时前
在 Electron 框架中实现数据库的连接、读取和写入
javascript·数据库·electron