스프링 프레임워크에 org.springframework.core.Constants 라는 클래스를 우연히 보게 되었다.
다른 클래스의 상수 값을 읽어내는 유틸리티 클래스다.
package spring.core;
public class MyConstants {
public static final int SIZE = 10;
public static final String HOSTS_PATH = "/etc/hosts";
public static final String DB_TABLE_USER = "tbl_user";
public static final String DB_TABLE_MENU = "tbl_menu";
public static final String DB_TABLE_AUTH = "tbl_auth";
}
위와 같이 상수를 정의한 클래스가 있다고 하자.
org.springframework.core.Constants 클래스는 생성자로 상수가 정의되어 있는 클래스를 인자로 받는다.
숫자와 문자열로 정의된 상수값을 읽어 올 수 있다.
또한 prefix를 기준으로 상수를 그루핑할 수 있다. MyConstants 클래스에서는 'DB_TABLE_' 문자열을 prefix로 사용할 수 있다.
잘못된 상수명을 사용한다면 리턴 값이 null이 아니라 org.springframework.core.ConstantException 이 throw 된다는 점은 유의해야 한다.
Constants constants = new Constants(MyConstants.class);
숫자 값을 읽을 때는 아래와 같이 사용한다.
Number number = constants.asNumber("SIZE");
문자열 값을 읽을 때는 아래와 같이 사용한다.
String hostsPath = constants.asString("HOSTS_PATH");
상수명을 그룹핑 할 때는 아래와 같이 사용한다.
Set
package spring.core;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.core.Constants;
public class ConstantsTest {
@Test
public void testConstants() throws Exception {
Constants constants = new Constants(MyConstants.class);
String hostsPath = constants.asString("HOSTS_PATH");
System.out.println(hostsPath);
Assert.assertEquals(MyConstants.HOSTS_PATH, hostsPath);
Number number = constants.asNumber("SIZE");
System.out.println("number: " + number);
Assert.assertEquals(MyConstants.SIZE, number.intValue());
Set names = null;
names = constants.getNames("DB_TABLE_");
System.out.println(names);
Assert.assertEquals(3, names.size());
names = constants.getNamesForProperty("dbTable");
System.out.println(names);
Assert.assertEquals(3, names.size());
}
}
댓글 없음:
댓글 쓰기