春天的旁边_春天@PropertySource

春天的旁边

Spring @PropertySource annotation is used to provide properties file to Spring Environment. This annotation is used with @Configuration classes.

Spring @PropertySource批注用于向Spring Environment提供属性文件。 此批注与@Configuration类一起使用。

Spring PropertySource annotation is repeatable, means you can have multiple PropertySource on a Configuration class. This feature is available if you are using Java 8 or higher version.

Spring PropertySource批注是可重复的,这意味着您可以在Configuration类上具有多个PropertySource。 如果您使用的是Java 8或更高版本,则此功能可用。

Spring PropertySource示例 (Spring PropertySource Example)

Let’s quickly go through a simple spring application where we will read Database configuration details from the property file and create the database connection. We will print some metadata information of the database to console.

让我们快速浏览一个简单的spring应用程序,在该应用程序中,我们将从属性文件中读取数据库配置详细信息并创建数据库连接。 我们将打印数据库的一些元数据信息以进行控制台。

Create a simple maven project and add Spring and MySQL dependencies. You can use any other database too for the example, just change the configurations accordingly.

创建一个简单的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>

Below image shows our project final structure, we will go through all the important components one by one.

下图显示了我们项目的最终结构,我们将逐一介绍所有重要组成部分。

Here is our class to create the Database Connection.

这是我们创建数据库连接的类。

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();
			}
		}
	}
}

NOTE: If you are creating a real-world application, you can use Spring ORM. This way spring will take care of database connection management and you can focus on writing business logic.

注意:如果要创建实际应用程序,则可以使用Spring ORM 。 通过这种方式,spring将负责数据库连接管理,您可以专注于编写业务逻辑。

Now let’s create the Spring Configuration class where we will use PropertySource annotation.

现在,让我们创建Spring Configuration类,在其中使用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;
    }
	
}

Notice that I am loading multiple properties files to the Spring environment. Let’s look at these property files content.

注意,我正在将多个属性文件加载到Spring环境中。 让我们看一下这些属性文件的内容。

db.properties

db.properties

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

root.properties

root.properties

APP_NAME=PropertySource Example

Let’s create the main class and get database details.

让我们创建主类并获取数据库详细信息。

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());

		// close the spring context
		context.close();
	}

}

Just run the above class as Java application, it will produce following output.

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

Getting DBConnection Bean for App: PropertySource Example
Creating DB Connection
Successfully Created DB Connection
MySQL
5.7.18
DBConnection close called

For better readability, I have removed the debug messages produced by spring logging to console.

为了提高可读性,我删除了Spring日志记录到控制台所产生的调试消息。

Spring @PropertySource多个文件– @PropertySources (Spring @PropertySource Multiple Files – @PropertySources)

There is another way to load multiple property files for a configuration class.

还有另一种为配置类加载多个属性文件的方法。

@PropertySources({
@PropertySource("classpath:db.properties"),
@PropertySource("classpath:root.properties")})
public class DBConfiguration {
}

From Java 8 onwards, PropertySource annotation became repeatable. For earlier java versions, @PropertySources was the way to provide multiple property files to the configuration class.

从Java 8开始,PropertySource批注变得可重复。 对于早期的Java版本, @PropertySources是提供多种属性文件中配置类的方式。

Spring PropertySource覆盖值 (Spring PropertySource Override Values)

We can load multiple property files to spring environment. If there are same keys present in multiple files, then the last property file loaded will override the earlier values. So if you are getting unwanted values for your property, check if the same key is present in any other property file and what is the order of loading these property files.

我们可以将多个属性文件加载到spring环境。 如果多个文件中存在相同的键,则最后加载的属性文件将覆盖先前的值。 因此,如果您的属性获得不必要的值,请检查其他任何属性文件中是否存在相同的键,以及加载这些属性文件的顺序是什么。

Spring PropertySource外部文件 (Spring PropertySource External File)

Sometimes our configuration files are present on specific location and they are not part of the project classpath. We can configure PropertySource to load property files from file system too.

有时,我们的配置文件位于特定的位置,并且不属于项目类路径。 我们也可以配置PropertySource以从文件系统加载属性文件。

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

Spring PropertySource环境变量 (Spring PropertySource Environment Variable)

Notice that the above configuration to read property file from the external location will work for my local system but not for someone else or on the server. We can also read system variables in PropertySource, so below configuration will work for everyone.

请注意,上述从外部位置读取属性文件的配置适用于我的本地系统,但不适用于其他人或服务器上。 我们还可以在PropertySource中读取系统变量,因此以下配置将对所有人适用。

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

Spring PropertySource忽略FileNotFoundException (Spring PropertySource ignore FileNotFoundException)

If the property file is not found, then we will get FileNotFoundException. Sometimes we don’t want to throw exception because our application can work with default values too. We can use PropertySource ignoreResourceNotFound to true to tell Spring framework to don’t throw exception if file is not found.

如果找不到属性文件,则将获取FileNotFoundException 。 有时我们不想抛出异常,因为我们的应用程序也可以使用默认值。 我们可以使用PropertySource ignoreResourceNotFoundtrue来告诉Spring框架如果找不到文件则不要抛出异常。

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

That’s all for Spring PropertySource Example. You can checkout source code and maven project from our GitHub Repository.

这就是Spring PropertySource示例的全部内容。 您可以从我们的GitHub存储库中签出源代码和Maven项目。

翻译自: https://www.journaldev.com/21440/spring-propertysource

春天的旁边

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值