Spring/spring_유용한것

spring annotation

slow333 2023. 6. 5. 22:48

@PostConstruct

bean 생성되기 전에 수행하는 annotation

 

@Qualifier

하나의 interface에 여러게의 구현체를 구현할 경우

interface를 autowired 할때 qualifier를 사용하면 구현체를 지정할 수 있음

용도에 따라 구현체를 구분해서 각자 용도에 맞게 사용할 때 유용 할 듯

 

@Value("${property name}")

application.properties 에 내용을 정의하고 class에서 갖다 사용할 수 있음

실제 production 할때 application.properties에 변수만 지정하고

실제 구현은 해당 시스템(linux, windows의 환경 변수에서 지정)에서 지정 할 때 유용

 

custom annotation

사용자 정의 annotation

우선 기본 골격을 이루는 class 생성(value, message 만 정의 나머지는 boil plate)

@Constraint(validatedBy = CourseCodeConstraintValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CourseCode {
//define default course code
String value() default "CustomAnnotation";
// define default error message
String message() default "must start with CustomAnnotation";
// define default groups
Class<?>[] groups() default {};
// define default payloads
Class<? extends Payload>[] payload() default {};
}

CourseCodeConstraintValidator 클래스를 만들고 조건을 정의

public class CourseCodeConstraintValidator implements ConstraintValidator<CourseCode, String> {

private String coursePrefix;

@Override
public void initialize(CourseCode theCourseCode) {
coursePrefix = theCourseCode.value();
}

@Override
public boolean isValid(String theCode, ConstraintValidatorContext context) {

boolean result;
if (theCode != null) result = theCode.startsWith(coursePrefix);
else result = true;
return result;
}
}

시작하는 문자를 정의하는 클래스  => 기본으로 CustomAnnotation 으로 정의 함(처음 클래스에서)

 

사용 방법(여기서는 validation을 위해 사용)

annotation 만 하면 기본 값이 정의되고, value, message를 적으면 override 됨

public class PersonInfo {
@NotBlank(message = "한자 이상")
@Size(min = 1, max = 50)
private String firstName;

@NotBlank(message = "한자 이상")
@Size(min = 1, max = 50)
private String lastName;

@NotBlank(message = "한자 이상")
@Email(message = "이메일 형식으로")
private String email;

@Pattern(regexp = "^[0-9]{11}", message = "11개의 숫자로...")
private String phoneNumber;

@CourseCode(value = "anno", message = "anno 로 시작해야함")
private String projectName
}

 

'Spring > spring_유용한것' 카테고리의 다른 글

jpa one to many 관련  (0) 2023.06.07
jpa tip  (0) 2023.06.06
data base-mysql  (0) 2023.06.06
html input type  (0) 2023.06.05
jsp, thymeleaf 동시에 사용하기...  (0) 2023.06.05