웹사이트 검색

스프링 @PropertySource


Spring @PropertySource 주석은 Spring 환경에 속성 파일을 제공하는 데 사용됩니다. 이 주석은 @Configuration 클래스와 함께 사용됩니다. Spring PropertySource 주석은 반복 가능하며 이는 Configuration 클래스에 여러 PropertySource를 가질 수 있음을 의미합니다. 이 기능은 Java 8 이상 버전을 사용하는 경우 사용할 수 있습니다.

스프링 PropertySource 예제

속성 파일에서 데이터베이스 구성 세부 정보를 읽고 데이터베이스 연결을 만드는 간단한 스프링 애플리케이션을 빠르게 살펴보겠습니다. 데이터베이스의 일부 메타데이터 정보를 콘솔에 출력합니다. 간단한 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이 데이터베이스 연결 관리를 처리하고 비즈니스 로직 작성에 집중할 수 있습니다. 이제 PropertySource 주석을 사용할 Spring 구성 클래스를 생성해 보겠습니다.

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

		// 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 @PropertySource 다중 파일 - @PropertySources

구성 클래스에 대한 여러 속성 파일을 로드하는 다른 방법이 있습니다.

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

Java 8부터 PropertySource 주석이 반복 가능해졌습니다. 이전 Java 버전의 경우 @PropertySources는 구성 클래스에 여러 속성 파일을 제공하는 방법이었습니다.

Spring PropertySource 재정의 값

스프링 환경에 여러 속성 파일을 로드할 수 있습니다. 여러 파일에 동일한 키가 있는 경우 마지막으로 로드된 속성 파일이 이전 값을 재정의합니다. 따라서 속성에 대해 원하지 않는 값을 얻는 경우 다른 속성 파일에 동일한 키가 있는지 확인하고 이러한 속성 파일을 로드하는 순서는 무엇인지 확인하십시오.

스프링 PropertySource 외부 파일

구성 파일이 특정 위치에 있고 프로젝트 클래스 경로의 일부가 아닌 경우가 있습니다. 파일 시스템에서 속성 파일을 로드하도록 PropertySource를 구성할 수도 있습니다.

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

Spring PropertySource 환경 변수

외부 위치에서 속성 파일을 읽는 위의 구성은 내 로컬 시스템에서는 작동하지만 다른 사람이나 서버에서는 작동하지 않습니다. 또한 PropertySource에서 시스템 변수를 읽을 수 있으므로 아래 구성이 모두에게 적합합니다.

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

Spring PropertySource는 FileNotFoundException을 무시합니다.

속성 파일을 찾을 수 없으면 FileNotFoundException이 발생합니다. 애플리케이션이 기본값으로도 작동할 수 있기 때문에 때때로 우리는 예외를 던지고 싶지 않습니다. PropertySource ignoreResourceNotFoundtrue로 사용하여 파일을 찾을 수 없는 경우 예외를 throw하지 않도록 Spring 프레임워크에 알릴 수 있습니다.

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

이것이 Spring PropertySource 예제의 전부입니다. GitHub 리포지토리에서 소스 코드와 maven 프로젝트를 체크아웃할 수 있습니다.

스프링 PropertySource 프로젝트