Spring **@PropertySource** 注解用于向 Spring 环境提供属性文件。此注解与 **@Configuration** 类一起使用。Spring **PropertySource** 注解是可重复的,意味着您可以在配置类上有多个 **PropertySource**。如果您使用的是 Java 8 或更高版本,则可以使用此功能。
Spring **PropertySource** 示例
让我们快速浏览一个简单的 Spring 应用程序,在这个应用程序中,我们将从属性文件中读取数据库配置详情,并创建数据库连接。我们将打印数据库的一些元数据信息到控制台。创建一个简单的 Maven 项目,并添加 Spring 和 MySQL 依赖项。您也可以为示例使用任何其他数据库,只需相应地更改配置。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
下面的图片显示了我们项目的最终结构,我们将逐个浏览所有重要的组件。这是我们创建数据库连接的类。
package com.journaldev.spring;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
private String driverClass;
private String dbURL;
private String userName;
private char[] password;
private Connection con;
public DBConnection(String driverClass, String dbURL, String userName, char[] password) {
this.driverClass = driverClass;
this.dbURL = dbURL;
this.userName = userName;
this.password = password;
}
public Connection getConnection() {
if (this.con != null)
return con;
Connection con = null;
try {
System.out.println("Creating DB Connection");
Class.forName(driverClass);
con = DriverManager.getConnection(dbURL, userName, String.valueOf(password));
System.out.println("Successfully Created DB Connection");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
this.con = con;
return con;
}
public void close() {
System.out.println("DBConnection close called");
if (this.con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
注意:如果您正在创建一个实际的应用程序,可以使用 Spring ORM。这样,Spring 将负责数据库连接管理,而您可以专注于编写业务逻辑。现在让我们创建 Spring 配置类,在这里我们将使用 PropertySource
注解。
package com.journaldev.spring;
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("classpath:db.properties")
@PropertySource("classpath:root.properties")
public class DBConfiguration {
@Autowired
Environment env;
@Bean
public DBConnection getDBConnection() {
System.out.println("Getting DBConnection Bean for App: "+env.getProperty("APP_NAME"));
DBConnection dbConnection = new DBConnection(env.getProperty("DB_DRIVER_CLASS"), env.getProperty("DB_URL"), env.getProperty("DB_USERNAME"), env.getProperty("DB_PASSWORD").toCharArray());
return dbConnection;
}
}
请注意,我正在加载多个属性文件到 Spring 环境中。让我们来看看这些属性文件的内容。 db.properties
#MYSQL 数据库配置
DB_DRIVER_CLASS=com.mysql.jdbc.Driver
DB_URL=jdbc:mysql://localhost:3306/Test
DB_USERNAME=journaldev
DB_PASSWORD=journaldev
root.properties
APP_NAME=PropertySource Example
让我们创建主类并获取数据库详细信息。
package com.journaldev.spring;
import java.sql.Connection;
import java.sql.SQLException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringMainClass {
public static void main(String[] args) throws SQLException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.journaldev.spring");
context.refresh();
DBConnection dbConnection = context.getBean(DBConnection.class);
Connection con = dbConnection.getConnection();
System.out.println(con.getMetaData().getDatabaseProductName());
System.out.println(con.getMetaData().getDatabaseProductVersion());
// 关闭 Spring 上下文
context.close();
}
}
只需运行上述类作为 Java 应用程序,它将生成以下输出。
Getting DBConnection Bean for App: PropertySource Example
Creating DB Connection
Successfully Created DB Connection
MySQL
5.7.18
DBConnection close called
为了更好的可读性,我已经删除了 Spring 记录到控制台的调试消息。
Spring @PropertySource 多个文件 – @PropertySources
还有另一种加载多个属性文件到配置类的方式。
@PropertySources({
@PropertySource("classpath:db.properties"),
@PropertySource("classpath:root.properties")})
public class DBConfiguration {
}
从Java 8开始,PropertySource注解变成了可重复的。对于早期的Java版本,@PropertySources
是向配置类提供多个属性文件的方法。
Spring PropertySource Override Values
我们可以加载多个属性文件到Spring环境中。如果多个文件中存在相同的键,则最后加载的属性文件将覆盖先前的值。因此,如果您的属性获取了不想要的值,请检查是否在任何其他属性文件中存在相同的键,以及加载这些属性文件的顺序。
Spring PropertySource External File
有时我们的配置文件位于特定位置,它们不是项目类路径的一部分。我们可以配置PropertySource以从文件系统加载属性文件。
@PropertySource("file:/Users/pankaj/db.properties")
Spring PropertySource Environment Variable
注意,上述配置从外部位置读取属性文件的设置在我的本地系统中有效,但对于其他人或服务器则不适用。我们还可以在PropertySource中读取系统变量,因此以下配置将适用于每个人。
@PropertySource("file:${HOME}/db.properties")
Spring PropertySource忽略FileNotFoundException
如果未找到属性文件,我们将收到FileNotFoundException
。有时我们不希望抛出异常,因为我们的应用程序也可以使用默认值运行。我们可以使用PropertySource ignoreResourceNotFound
将 true
来告诉Spring框架如果未找到文件,则不要抛出异常。
@PropertySource(value = "classpath:root.properties", ignoreResourceNotFound=true)
这就是Spring PropertySource示例的全部内容。您可以从我们的GitHub存储库中检出源代码和Maven项目。
Source:
https://www.digitalocean.com/community/tutorials/spring-propertysource