Spring IoC Container 10부

Spring IoC 컨테이너와 빈 - 10부

백기선님의 강의인 Spring 프레임워크 핵심 기술 편의 IoC Container를 학습한 내용을 정리한 글

ResourceLoader

IoC Container의 마지막 파트인 ResourceLoader에 대해 알아보자.

역시나 ApplicationContext의 또 다른 기능 중 하나이다.

인터페이스 이름에서 알 수 있듯이 리소스를 읽어오는 인터페이스이다.

ResourceLoader의 메소드인 getResource 메소드에 문자열 인자값을 줄 수 있다.

이 문자열은 자원의 위치를 넣어줄 수 있고 해당 위치에 있는 자원을 가져올 수 있게 된다.

Resource 추상화

org.springframework.core.io.Resource

Spring은 java.net.URL을 추상화하였음

스프링 내부에서 많이 사용하는 인터페이스이다.

이 인터페이스의 구현체로는 다음과 같다.

  • UrlResource : 기본으로 지원하는 프로토콜 http,https,ftp,file,jar
  • ClassPathResource : 접두어를 classpath:로 붙여서 찾아가게 함
  • ServletContextResource: WebApplicationContext 루트에서 상대 경로로 리소스를 찾는다. 가장 많이 사용함.
  • FileSystemResource

리소스에 따로 명시하지않으면 기본적으로 WebApplicationContext의 상대경로로 리소스를 찾아간다.

때문에 명시적으로 경로를 지정하고 싶다면 접두어로 classpath나 file을 붙여 찾아가게 하자.

명시하지않으면 default는 WebApplicationContext의 상대 경로

Validation 추상화

org.springframework.validation.Validator

애플리케이션에서 사용하는 객체 검증용 인터페이스이다.

특징으로는 3가지가 있다.

  1. 어떤 계층과도 관계가 없다.

즉 모든 계층(웹,서비스,데이터)에서 사용해도 된다는 말이다.

  1. 구현체 중 하나로 Bean Validation 2.0까지 지원한다.

  2. DataBinder에 들어가 바인딩 할 때 같이 사용되기도 한다.

Bean Validation이란?

Java EE 표준 스펙 중 하나이다.

어노테이션을 통해 빈의 데이터를 검증할 수 있는 기능을 제공한다.

Validator

public class Event {
  Integer id;
  String title;

  public Integer getId(){
    return id;
  }

  public void setId(Integer id){
    this.id = id;
  }

  public String getTitle(){
    return title;
  }

  public void setTitle(String title){
    this.title = this.title;
  }
}

위의 자바 객체에 title이 null이 되면 안된다고 해보자.

이를 위해 Validator 인터페이스를 구현하자.


public class EventValidator implements Validator{
  @Override
  public boolean supports(Class<?> clazz){
    return Event.class.equals(clazz);
  }

  @Override
  public void validate(Object target, Errors erros){
    ValidationUtils.rejectIfEmptyOrWhitespace(erros,"title","notempty","Empty title is not allowed.");
  }
}

Validator 인터페이스를 구현하면 2가지 메소들르 구현해야만 한다.

supports() 메소드와 validate() 메소드이다.

supports 메소드는 해당 객체가 현재 검증할 객체가 맞는지 검사하는 메소드이다.

validate 메소드는 그 객체가 개발자가 정의한 조건에 부합하는지를 검증하는 메소드이다.

@Component
public class AppRunner implements ApplicationRunner{
  @Override
  public void run(ApplicationArguments args) throws Exception{
    Event event = new Event();
    EventValidator eventValidator = new EventValidator();
    Erros erros = new BeanPropertyBindingResult(event,"event");

    eventValidator.validate(event,errors);

    System.out.println(erros.hasErrors());
    errors.getAllErrors().forEach( e-> {
      System.out.println("====error code====");
      Arrays.stream(e.getCodes()).forEach(System.out::println);
      System.out.println(e.getDefaultMessage());
    });
  }
}

Erros는 Spring MVC에서 자동으로 만들어주기 때문에 직접 만들어줄 일은 드물다.

그러나 여기서는 예제를 테스트해보기 위해 직접 구현하였다.

만약 스프링 부트 2.0.5 이상 버전을 사용할 때는 이보다 훨씬 더 편한 방법으로 검증이 가능하다.

우선 아까 본 Validator 인터페이스가 LocalValidatorFactoryBean라는 이름의 빈으로 자동 등록이 된다.

그래서 Springboot에서는 해당 객체에 @NotEmpty 어노테이션을 붙여서 검증이 가능하다.

public class Event {
  Integer id;

  @NotEmpty
  String title;

  @Min(0)
  Integer limit;

  @Email
  String email;

  public Integer getId(){
    return id;
  }

  public void setId(Integer id){
    this.id = id;
  }

  public String getTitle(){
    return title;
  }

  public void setTitle(String title){
    this.title = this.title;
  }

  public Integer getLimit(){
    return limit;
  }

  public void setemail(Integer email){
    this.email = this.email;
  }

    public String getemail(){
    return email;
  }

  public void setLimit(Integer limit){
    this.limit = this.limit;
  }
}

@NotNull 외에도 해당 문자열이 이메일인지 검증해주는 @Email 어노테이션이나 크기를 제한할 수 있는 @Min 어노테이션으로 간단하게 검증이 가능하다.

컬렉션 프레임워크의 사이즈를 검증하는 @Size 어노테이션 또한 존재한다.

만약 NotNull이나 사이즈 제한, 이메일 같이 간단한 검증의 경우 어노테이션을 사용할 수 있지만 복잡한 비즈니스 로직의 경우라면 Validator를 구현하여 로직을 만들어 검증하는 것 또한 가능할 것이다.

Reference

인프런 백기선님의 스프링 프레임워크 핵심 기술 강좌



© 2022. by minkuk

Powered by minkuk