본문 바로가기
IT_Developers/JAVA

Spring - @Validated 란? 무엇인가? / @Valid와 차이점

by 고코더 2021. 6. 16.

@Validated를 알아보자

 

 

안녕하세요.

고코더 입니다.

 

 

오늘은 스프링에서 데이터 유효성 검증에 사용하는 @Validated  라는 어노테이션을 배워 보려고 합니다. 

오래전부터 자바를 쓰신 분들은 @Valid 라는 단어가 더 익숙하지만 오늘은 스프링에서 제공하는 @Validated 를 알아보도록 하겠습니다.

 

1.   @Valid와 차이

 

우선 기존의 존재하던 데이터 유효성 검사 메서드는 기존 자바의 기술입니다. "javax.validation.Valid" 입니다. 자바에 존재합니다. 서블릿 기술입니다. 찾아보니 현재

JSR 380까지 출시되어 있습니다.  ( The Java Community Process(SM) Program - JSRs- Java Specification Requests - detail JSR# 380 ) 

하지만 스프링은 이를 좀 더 업그레이드했습니다. 

 

/*
 * Bean Validation API
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package javax.validation;

import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/**
 * Marks a property, method parameter or method return type for validation cascading.
 * <p>
 * Constraints defined on the object and its properties are be validated when the
 * property, method parameter or method return type is validated.
 * <p>
 * This behavior is applied recursively.
 *
 * @author Emmanuel Bernard
 * @author Hardy Ferentschik
 */
@Target({ METHOD, FIELD, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
public @interface Valid {
}

 

 

2.  @Validated이란

 

해당 기능은 스프링에서 제공하는 인터페이스입니다. "package org.springframework.validation.annotation" 실무에서는 컨트롤러를 @ModelAttribute 모델에 바인딩하는 데 사용합니다. 해당 인터페이스는 두 개의 메세드로 구성되어 있습니다. 그리고 @Validated는 @Valid의 기능을 포함합니다. 

 

- supports(Class), 매개변수로 전달된 클래스를 검증하여 반환

- validate(Object, org.springframework.validation.Errors), 매개변수로 전달된 객체 검증하여 반환

 

/*
 * Copyright 2002-2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.validation.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Variant of JSR-303's {@link javax.validation.Valid}, supporting the
 * specification of validation groups. Designed for convenient use with
 * Spring's JSR-303 support but not JSR-303 specific.
 *
 * <p>Can be used e.g. with Spring MVC handler methods arguments.
 * Supported through {@link org.springframework.validation.SmartValidator}'s
 * validation hint concept, with validation group classes acting as hint objects.
 *
 * <p>Can also be used with method level validation, indicating that a specific
 * class is supposed to be validated at the method level (acting as a pointcut
 * for the corresponding validation interceptor), but also optionally specifying
 * the validation groups for method-level validation in the annotated class.
 * Applying this annotation at the method level allows for overriding the
 * validation groups for a specific method but does not serve as a pointcut;
 * a class-level annotation is nevertheless necessary to trigger method validation
 * for a specific bean to begin with. Can also be used as a meta-annotation on a
 * custom stereotype annotation or a custom group-specific validated annotation.
 *
 * @author Juergen Hoeller
 * @since 3.1
 * @see javax.validation.Validator#validate(Object, Class[])
 * @see org.springframework.validation.SmartValidator#validate(Object, org.springframework.validation.Errors, Object...)
 * @see org.springframework.validation.beanvalidation.SpringValidatorAdapter
 * @see org.springframework.validation.beanvalidation.MethodValidationPostProcessor
 */
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Validated {

	/**
	 * Specify one or more validation groups to apply to the validation step
	 * kicked off by this annotation.
	 * <p>JSR-303 defines validation groups as custom annotations which an application declares
	 * for the sole purpose of using them as type-safe group arguments, as implemented in
	 * {@link org.springframework.validation.beanvalidation.SpringValidatorAdapter}.
	 * <p>Other {@link org.springframework.validation.SmartValidator} implementations may
	 * support class arguments in other ways as well.
	 */
	Class<?>[] value() default {};

}

 

3.어노테이션으로 사용법

@Validated // 어노테이션 추가
@Service
public class GocoderService {
    public void Contact(@Valid GocoderContact gocoderContact) { 
    }
}

 

4.컨트롤러에서 사용법

@RequestMapping("/gocoder.do")
public ModelAndView gocoderController(@Validated GocoderDto GC) throws Exception {

}

 

 

댓글0