properties파일에 대해서 알아보자
먼저 properties파일은 파일에 마지막에 붙는 확장자가 .properties 라고 붙는
파일을 의미한다.
그럼 이걸 왜 쓰고 언제 쓰느냐?
바로 프로그램 실행 중 변하지 않는 값을 저장하게 어디서든 쉽게 꺼내서 사용하기 위해 쓴다.
ex) jdbc정보라든가, 내가 정한 특정값(절대 안변하는값)
원하는 곳에 .properties 의 확장자로 저장을 하고
그 안에 위에 예시의 정보들을 넣어둔다면 내가 원할때
바로바로 꺼내서 사용할 수 있을것이다.
기본적으로 properties파일에
한글 등을 치면 알아서 값이 바뀌므로 우리가 알아보려면
이클립스에서 properties 에디터 설치가 필수다.
Help > Install New Software 에서
주소값으로 http://propedit.sourceforge.jp/eclipse/updates
이것을 넣어서 다운받고 체크박스가 뜨면 맨밑에 있는
Properties editor만 선택 후 다운받고
계속하시겠습니까? 뜨면 install anyway클릭하면 알아서 깔린다.
그후 껏다키면 한글을 쳐도 이상한 문자로 변환되지 않는
properties파일이 된다
그럼 성공이다.
properties파일을 만들때
파일의 위치와 폴더는 사용자가 지정해주는 것으므로
원하는곳에 만들면된다
(WebContent폴더 안쪽에 폴더 생성 후 일단 만들어보자)
필자는 이렇게 properties파일을 만들었다.
그 후 컨트롤러에서 어떻게 다루는지가 핵심이다.
@Controller
//@PropertySource("/WEB-INF/properties/data1.properties") //한개 사용시 @PropertySource, 2개이상은 @PropertySources
//@PropertySource("/WEB-INF/properties/data2.properties")
/*
* @PropertySource(value = { "/WEB-INF/properties/data1.properties",
* "/WEB-INF/properties/data2.properties" })
*/
@PropertySources({
@PropertySource("/WEB-INF/properties/data1.properties"),
@PropertySource("/WEB-INF/properties/data2.properties")
})
/*
위에 보면 크게 properties파일을 저장하는 방법이 3가지이다.
1번째 : 그냥 @PropertySource로 다 쓰기
2번째: @PropertySource쓰고 value를 배열로 주기
3번째 : @PropertySources를 사용한 후 그 안에 배열로 @PropertySource넣기
3번째가 가장 좋은 것 같다(물론 3가지는 properties파일 여러개 사용시이고
한개만 사용시에는 그냥 @PropertySource만 쓰면된다)
*/
public class TestControlloer {
//@PropertySource와 사용한 클래스는 클래스의 내용에서 @Value("${ ~ }") 태그와 함께 사용한다.
@Value("${aaa.a1}")
private int a1; //숫자는 int, string 중 정할 수 있다.
@Value("${aaa.a2}")
private String a2;
@Value("${bbb.b1}")
private int b1;
@Value("${bbb.b2}")
private String b2;
@Value("${ccc.c1}")
private String c1;
@Value("${ccc.c2}")
private String c2;
@Value("${ddd.d1}")
private String d1;
@Value("${ddd.d2}")
private String d2;
@GetMapping("/test1")
public String test1() {
System.out.println("aaa.a1 : "+a1);
System.out.println("aaa.a2 : "+a2);
System.out.println("bbb.b1 : "+b1);
System.out.println("bbb.b2 : "+b2);
System.out.println("ccc.c1 : "+c1);
System.out.println("ccc.c2 : "+c2);
System.out.println("ddd.d1 : "+d1);
System.out.println("ddd.d2 : "+d2);
return "test1";
}
}
주석을 한번 더 적겠다.
위에 보면 크게 properties파일을 저장하는 방법이 3가지이다.
1번째 : 그냥 @PropertySource로 다 쓰기
2번째: @PropertySource쓰고 value를 배열로 주기
3번째 : @PropertySources를 사용한 후 그 안에 배열로 @PropertySource넣기
3번째가 가장 좋은 것 같다
(물론 3가지 방법은 properties파일 여러개 사용시이고
properties한개만 사용시에는 그냥 @PropertySource만 쓰면된다)
@PropertySource(" 경로위치 ")를 적어주도록 하자.
그리고 @PropertySource 는 @Value와 함께 사용하는 것이다.
@Value("${ 프로퍼티이름}") 을 쓰면된다.
그리고 숫자는 int로 받으면 int값이 되고
String으로 받으면 문자열이 된다.
콘솔 결과값은 이렇게된다.
스프링 유효성검사 properties error <form:form> (0) | 2022.02.02 |
---|---|
스프링 Properties파일 Message로 등록하고 사용하기 예제 (0) | 2022.01.30 |
스프링 Cookie 활용방법(jsp방식보다 훨신간편) @CookieValue 예제 (0) | 2022.01.27 |
스프링 applicationScope의 bean주입 (0) | 2022.01.27 |
spring ApplicationScope와 ServletContext의 개념과 예제 (0) | 2022.01.26 |
댓글 영역