Spring@PropertySource
Spring @PropertySource批注用于向Spring Environment提供属性文件。
这个注解与@Configuration类一起使用。
Spring PropertySource批注是可重复的,这意味着您可以在Configuration类上具有多个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.theitroad.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 Configuration类,其中使用PropertySource批注。
package com.theitroad.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 Database Configurations DB_DRIVER_CLASS=com.mysql.jdbc.Driver DB_URL=jdbc:mysql://localhost:3306/Test DB_USERNAME=theitroad DB_PASSWORD=theitroad
root.properties
APP_NAME=PropertySource Example
让我们创建主类并获取数据库详细信息。
package com.theitroad.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.theitroad.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());
//close the spring context
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覆盖值
我们可以将多个属性文件加载到spring环境。
如果多个文件中存在相同的键,则最后加载的属性文件将覆盖较早的值。
因此,如果您获得了属性的多余值,请检查其他任何属性文件中是否存在相同的键,以及加载这些属性文件的顺序是什么。
Spring PropertySource外部文件
有时,我们的配置文件位于特定的位置,而不是项目类路径的一部分。
我们也可以配置PropertySource以从文件系统加载属性文件。
@PropertySource("file:/Users/hyman/db.properties")
Spring PropertySource环境变量
请注意,上述从外部位置读取属性文件的配置适用于我的本地系统,但不适用于其他人或者服务器上。
我们还可以在PropertySource中读取系统变量,因此以下配置将对所有人适用。
@PropertySource("file:${HOME}/db.properties")
Spring PropertySource忽略FileNotFoundException
如果找不到属性文件,那么我们将得到FileNotFoundException。
有时我们不想抛出异常,因为我们的应用程序也可以使用默认值。
我们可以使用PropertySource的ignoreResourceNotFound到true来告诉Spring框架如果找不到文件则不要抛出异常。
@PropertySource(value = "classpath:root.properties", ignoreResourceNotFound=true)

