데브코스 W4D4

코끼릭·2022년 4월 8일
0

TIL

목록 보기
13/36

Environment

ApplicationContext에서 제공하는 또 다른 중요한 기능중의 하나로 스프링 환경 설정인 Profiles, Property과 관련된 인터페이스이다. 실제 ApplicationContext의 인터페이스 구현 코드를 살펴보면 환경 설정과 관련된 EnvironmentCapable이라는 인터페이스를 확장하고 있는 의존 관계를 형성하고 있다. (Java에서는 인터페이스 간의 상속을 통한 확장이 가능하다.) Environment는 ApplicationContext의 getEnvironment메소드를 통해 설정파일에 대한 정보에 접근하여 사용하면 된다.

Profiles

스프링 어플케이션을 개발할 때 개발 환경에 따라 변경이 되어야하는 빈 조합을 간단한 이름과 아노테이션을 통해 간단하게 전환할 수 있게 된다. 특정 빈 설정 세팅 방법은 해당 빈 설정 클래스에 @Profile("이름")을 설정한 후 Intellij IDE의 경우 Run>Edit Configurations>Active Profiles에 원하는 프로파일명을 작성하면 원하는 빈 설정으로 전환이 가능하다.

@Configuration
@Profile("dev")
public class TestAppContext {

}
...
	//메소드 자체에도 사용이 가능하다.
    @Profile("dev")
    public void test() {

    }
...
//생성한 프로파일을 활성화 시켜야 빈 설정이 적용된다.
@ActiveProfiles("dev")
public class userServiceTest {

}	

Property

db 연결정보나 db 드라이버 클래스, URL, 로그인 계정 정보 등 개발 환경에 따라 자주 변경되는 설정 정보를 쉽게 코드에서 적용하고 작성이 용이한 텍스트 파일 형태로 저장해서 사용할 수 있는데 .properties 또는 .yaml을 형태 중 하나로 작성해서 사용할 수 있다. 작성은 키와 값 형태로 프로퍼티파일을 정의하면 된다.

작성된 property 정보를 사용할 때는 ApplicationContext 클래스 위에 @PropertySource("설정파일 경로명")를 넣어주면 해당 프로퍼티 파일 내용이 Environment 오브젝트에 저장되고(@AutoWired를 사용해서 DI) 이를 getProperty()를 이용해서 가져올 수 있다. 추가로 @Value("${프로퍼티 키}")를 이용해 클래스 필드에 직접 주입받을 수도 있다. (이 경우 InitializingBean 인터페이스를 상속받은 클래스에 주입가능하다.)

Environment env = voucherContext.getEnvironment();
String fileName = env.getProperty("customer_blacklist");	

Resource

외부 리소스(이미지 파일, 텍스트 파일, 키파일)을 읽을 경우 가져오기 위한 인터페이스로 스프링에서는 Resource를 제공하고 이를 구현한 클래스는 크게 다음과 같다.

  • ClassPathResource : 클래스패스 상 리소스
  • FileSystemResource: 파일 시스템
  • PathResource : URL 상의 웹 리소스
  • SevletContextResource: 웹 어플리케이션 리소스

각 구현 클래스를 사용할 수도 있지만 ResourceLoader 인터페이스를 사용해 불러오는 리소스의 정보를 알아서 파악해 필요한 구현 클래스를 반환 받아서 사용하는 것이 더 편리하다.

package resource;

...

public static void main(String[] args) {
  AnnotationConfigApplicationContext appContext =
  new AnnotationConfigApplicationContext(AppContextConfig.class);
  MyResource myResource = appContext.getBean(MyResource.class);

  Resource resource1 = myResource.getResource("classpath:property.properties");
  System.out.println(resource1.getClass());

  Resource resource2 = myResource.getResource("http://www.resource.com");
  System.out.println(resource2.getClass());
}

Resource R/W

public static void main(String[] args) throws IOException {
  AnnotationConfigApplicationContext appContext =
  new AnnotationConfigApplicationContext(AppContextConfig.class);
  MyResource myResource = appContext.getBean(MyResource.class);
  
  //자료 읽기
  Resource resource = myResource.getResource("classpath:resource.txt");
  InputStream inStream = resource.getInputStream();
  String content = StreamUtils.copyToString(inStream, StandardCharsets.UTF_8);
  System.out.println(content);
  inStream.close();
  //자료 쓰기
  Resource resource = myResource.getResource("classpath:resource.txt");
  File file = resource.getFile();
  OutputStream outStream = new FileOutputStream(file);
  StreamUtils.copy("Goodbye World".getBytes(), outStream);
  outStream.close();
}

리소스 사용 예제

profile
ㅇㅅㅇ

0개의 댓글