스프링 @Value 주석
스프링 @Value 주석.
Spring @Value - 기본값
@Value 주석을 사용하여 클래스 속성에 기본값을 할당할 수 있습니다.
@Value("Default DBConfiguration")
private String defaultName;
@Value 어노테이션 인수는 문자열만 가능하지만 Spring은 이를 지정된 유형으로 변환하려고 시도합니다. 아래 코드는 잘 작동하고 부울 및 정수 값을 변수에 할당합니다.
@Value("true")
private boolean defaultBoolean;
@Value("10")
private int defaultInt;
Spring @Value - Spring 환경 속성
@Value("${APP_NAME_NOT_FOUND}")
private String defaultAppName;
스프링 환경 속성에서 키를 찾을 수 없으면 속성 값은 $ {APP_NAME_NOT_FOUND}
가 됩니다. 스프링 환경 속성에서 키가 누락된 경우 할당될 기본값을 할당할 수 있습니다.
@Value("${APP_NAME_NOT_FOUND:Default}")
private String defaultAppName;
Spring @Value - 시스템 환경
Spring 환경이 채워지면 모든 시스템 환경 변수를 읽고 속성으로 저장합니다. 따라서 @Value 주석을 사용하여 시스템 변수도 할당할 수 있습니다.
@Value("${java.home}")
private String javaHome;
@Value("${HOME}")
private String homeDir;
스프링 @값 - SpEL
@Value 주석과 함께 Spring Expression Language를 사용할 수도 있습니다. 따라서 SpEL을 사용하여 Java 홈 시스템 속성도 읽을 수 있습니다.
@Value("#{systemProperties['java.home']}")
private String javaHome;
메서드가 있는 Spring @Value
@Value 주석이 인수와 직접 사용되는 경우.
@Value("Test")
public void printValues(String s, String v){} //both 's' and 'v' values will be 'Test'
@Value("Test")
public void printValues(String s, @Value("Data") String v){}
// s=Test, v=Data
스프링 @Value 예제
@Value 주석을 사용하여 속성을 읽고 클래스 변수에 할당하는 간단한 Spring 애플리케이션을 만들어 봅시다. maven 프로젝트를 만들고 스프링 코어 종속성을 추가합니다.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
package com.journaldev.spring;
import org.springframework.beans.factory.annotation.Value;
public class DBConnection {
@Value("${DB_DRIVER_CLASS}")
private String driverClass;
@Value("${DB_URL}")
private String dbURL;
@Value("${DB_USERNAME}")
private String userName;
@Value("${DB_PASSWORD}")
private char[] password;
public DBConnection() {
}
public void printDBConfigs() {
System.out.println("Driver Class = " + driverClass);
System.out.println("DB URL = " + dbURL);
System.out.println("User Name = " + userName);
// Never do below in production environment :D
System.out.println("Password = " + String.valueOf(password));
}
}
이제 Configuration 클래스를 만들고 DBConnection 클래스에 @Bean 메서드를 제공해야 합니다.
package com.journaldev.spring;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:db.properties")
@PropertySource(value = "classpath:root.properties", ignoreResourceNotFound = true)
public class DBConfiguration {
@Value("Default DBConfiguration")
private String defaultName;
@Value("true")
private boolean defaultBoolean;
@Value("10")
private int defaultInt;
@Value("${APP_NAME_NOT_FOUND:Default}")
private String defaultAppName;
// @Value("#{systemProperties['java.home']}")
@Value("${java.home}")
private String javaHome;
@Value("${HOME}")
private String homeDir;
@Bean
public DBConnection getDBConnection() {
DBConnection dbConnection = new DBConnection();
return dbConnection;
}
@Value("Test")
public void printValues(String s, @Value("another variable") String v) {
System.out.println("Input Argument 1 =" + s);
System.out.println("Input Argument 2 =" + v);
System.out.println("Home Directory = " + homeDir);
System.out.println("Default Configuration Name = " + defaultName);
System.out.println("Default App Name = " + defaultAppName);
System.out.println("Java Home = " + javaHome);
System.out.println("Boolean = " + defaultBoolean);
System.out.println("Int = " + defaultInt);
}
}
다음은 주석 기반 스프링 컨텍스트를 만드는 기본 클래스입니다.
package com.journaldev.spring;
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();
System.out.println("Refreshing the spring context");
DBConnection dbConnection = context.getBean(DBConnection.class);
dbConnection.printDBConfigs();
// close the spring context
context.close();
}
}
클래스를 실행하면 다음 출력이 생성됩니다.
Input Argument 1 =Test
Input Argument 2 =another variable
Home Directory = /Users/pankaj
Default Configuration Name = Default DBConfiguration
Default App Name = Default
Java Home = /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
Boolean = true
Int = 10
Refreshing the spring context
Driver Class = com.mysql.jdbc.Driver
DB URL = jdbc:mysql://localhost:3306/Test
User Name = journaldev
Password = journaldev
컨텍스트가 사용자 요청을 처리할 준비가 되기 전에 구성 클래스 printValues()
가 호출된다는 점에 유의하십시오. Spring @Value 주석 예제는 여기까지입니다. GitHub 리포지토리에서 예제 코드를 다운로드할 수 있습니다.
Spring @Value 주석 프로젝트