이번에는 직접 애너테이션을 직접 만들어보았다.

 

@Qualifier("mainDiscountPolicy") 여기에는 문제가 한가지 있다.

문자는 컴파일시 타입 체크가 안된다. 이 문제를 애너테이션을 만들어서 해결할 수 있다.

 

package hello.core.annotation;

import org.springframework.beans.factory.annotation.Qualifier;

import java.lang.annotation.*;

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@Qualifier("mainDiscountPolicy")
public @interface MainDiscountPolicy {
}

기존 @Qualifier에 들어있는 애너테이션들을 가져오고 추가로 @Qualifier를 붙여주면 완성이다.

 

package hello.core.discount;

import hello.core.annotation.MainDiscountPolicy;
import hello.core.member.Grade;
import hello.core.member.Member;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

@Component
@MainDiscountPolicy
public class RateDiscountPolicy implements DiscountPolicy{

    private int discountPercent = 10;

    @Override
    public int discount(Member member, int price) {
        if(member.getGrade() == Grade.VIP){
            return price * discountPercent / 100;
        } else{
            return 0;
        }
    }
}

그리고 구현클래스에 보기 깔끔하게 붙여주었다.

 

    @Autowired
    public OrderServiceImpl(MemberRepository memberRepository, @MainDiscountPolicy DiscountPolicy discountPolicy) {
        this.memberRepository = memberRepository;
        this.discountPolicy = discountPolicy;
    }

이렇게 가져다가 쓰는 클래스의 생성자 파라미터에 붙여주면 깔끔하게 쓸 수 있다.

 

애너테이션은 상속이라는 개념이 없다. 이렇게 여러 애너테이션을 모아서 사용하는 기능은 스프링이 제공하는 기능이다.

+ Recent posts