Spring @属性源

Spring @PropertySource 注释用于向 Spring Environment 提供属性文件. 此注释用于 @Configuration 类. Spring PropertySource 注释是可重复的,这意味着您可以在一个 Configuration 类上拥有多个 PropertySource。

春天财产实例

让我们快速通过一个简单的春季应用程序,我们将从属性文件中读取数据库配置详细信息,并创建数据库连接。我们会将数据库的一些元数据信息打印到控制台上。创建一个简单的maven项目并添加 Spring 和 MySQL 依赖性。

 1<dependency>
 2    <groupId>org.springframework</groupId>
 3    <artifactId>spring-context</artifactId>
 4    <version>5.0.6.RELEASE</version>
 5</dependency>
 6<dependency>
 7    <groupId>mysql</groupId>
 8    <artifactId>mysql-connector-java</artifactId>
 9    <version>5.1.46</version>
10</dependency>

Below image shows our project final structure, we will go through all the important components one by one. Spring PropertySource Example Here is our class to create the Database Connection.

 1package com.journaldev.spring;
 2
 3import java.sql.Connection;
 4import java.sql.DriverManager;
 5import java.sql.SQLException;
 6
 7public class DBConnection {
 8
 9    private String driverClass;
10    private String dbURL;
11    private String userName;
12    private char[] password;
13    private Connection con;
14
15    public DBConnection(String driverClass, String dbURL, String userName, char[] password) {
16    	this.driverClass = driverClass;
17    	this.dbURL = dbURL;
18    	this.userName = userName;
19    	this.password = password;
20    }
21
22    public Connection getConnection() {
23    	if (this.con != null)
24    		return con;
25
26    	Connection con = null;
27    	try {
28    		System.out.println("Creating DB Connection");
29    		Class.forName(driverClass);
30    		con = DriverManager.getConnection(dbURL, userName, String.valueOf(password));
31    		System.out.println("Successfully Created DB Connection");
32    	} catch (ClassNotFoundException | SQLException e) {
33    		e.printStackTrace();
34    	}
35    	this.con = con;
36    	return con;
37    }
38
39    public void close() {
40    	System.out.println("DBConnection close called");
41    	if (this.con != null) {
42    		try {
43    			con.close();
44    		} catch (SQLException e) {
45    			e.printStackTrace();
46    		}
47    	}
48    }
49}

注意:如果您正在创建一个真实世界的应用程序,您可以使用 Spring ORM

 1package com.journaldev.spring;
 2
 3import org.springframework.beans.factory.annotation.Autowired;
 4import org.springframework.context.annotation.Bean;
 5import org.springframework.context.annotation.Configuration;
 6import org.springframework.context.annotation.PropertySource;
 7import org.springframework.core.env.Environment;
 8
 9@Configuration
10@PropertySource("classpath:db.properties")
11@PropertySource("classpath:root.properties")
12public class DBConfiguration {
13
14    @Autowired
15    Environment env;
16    
17    @Bean
18    public DBConnection getDBConnection() {
19    	System.out.println("Getting DBConnection Bean for App: "+env.getProperty("APP_NAME"));
20    	DBConnection dbConnection = new DBConnection(env.getProperty("DB_DRIVER_CLASS"), env.getProperty("DB_URL"), env.getProperty("DB_USERNAME"), env.getProperty("DB_PASSWORD").toCharArray());
21        return dbConnection;
22    }
23    
24}

请注意,我正在上传多个属性文件到春季环境. 让我们看看这些属性文件的内容. db.properties

1#MYSQL Database Configurations
2DB_DRIVER_CLASS=com.mysql.jdbc.Driver
3DB_URL=jdbc:mysql://localhost:3306/Test
4DB_USERNAME=journaldev
5DB_PASSWORD=journaldev

原标题: 财产

1APP_NAME=PropertySource Example

让我们创建主类,并获取数据库细节。

 1package com.journaldev.spring;
 2
 3import java.sql.Connection;
 4import java.sql.SQLException;
 5
 6import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 7
 8public class SpringMainClass {
 9
10    public static void main(String[] args) throws SQLException {
11    	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
12    	context.scan("com.journaldev.spring");
13    	context.refresh();
14
15    	DBConnection dbConnection = context.getBean(DBConnection.class);
16
17    	Connection con = dbConnection.getConnection();
18
19    	System.out.println(con.getMetaData().getDatabaseProductName());
20    	System.out.println(con.getMetaData().getDatabaseProductVersion());
21
22    	// close the spring context
23    	context.close();
24    }
25
26}

只需运行上述类作为Java应用程序,它将产生以下输出。

1Getting DBConnection Bean for App: PropertySource Example
2Creating DB Connection
3Successfully Created DB Connection
4MySQL
55.7.18
6DBConnection close called

为了更好的可读性,我已经删除了由春天登录到控制台产生的调试消息。

春天 @PropertySource 多个文件 - @PropertySources

另一种方法是将多个属性文件加载到一个配置类。

1@PropertySources({
2@PropertySource("classpath:db.properties"),
3@PropertySource("classpath:root.properties")})
4public class DBConfiguration {
5}

从Java 8开始,PropertySource的注释成为可重复的,对于早期Java版本来说,@PropertySources是为配置类提供多个属性文件的方式。

春天财产超越价值观

我们可以将多个属性文件加载到春季环境中,如果在多个文件中存在相同的密钥,那么上次加载的属性文件将超出以前的值,因此,如果您正在为您的属性获得不必要的值,请检查同一个密钥是否存在于任何其他属性文件中,以及加载这些属性文件的顺序是什么。

Spring PropertySource 外部文件

有时我们的配置文件存在于特定位置,而不是项目类路径的一部分,我们也可以配置 PropertySource 来从文件系统上加载属性文件。

1@PropertySource("file:/Users/pankaj/db.properties")

春季物业环境变量

请注意,上面的配置以从外部位置读取属性文件将适用于我的本地系统,但不会适用于其他人或服务器上。

1@PropertySource("file:${HOME}/db.properties")

Spring PropertySource 忽略 FileNotFoundException

如果属性文件无法找到,那么我们会得到FileNotFoundException。有时我们不想扔例外,因为我们的应用程序也可以使用默认值。

1@PropertySource(value = "classpath:root.properties", ignoreResourceNotFound=true)

你可以从我们的GitHub存储库中查找源代码和maven项目。

春季财产资源项目

Published At
Categories with 技术
Tagged with
comments powered by Disqus