더북(TheBook)

스프링에서 자신만의 조건을 작성하는 방법은 간단하다. Condition 인터페이스를 상속받고 matches() 메서드를 오버라이드하면 된다. 다음 조건 클래스는 JdbcTemplate이 클래스패스에 있을 때만 통과한다.


package readinglist;
 
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
 
public class JdbcTemplateCondition implements Condition {
 
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        try {
            context.getClassLoader().loadClass(“org.springframework.jdbc.core.JdbcTemplate”);
            return true;
        } catch (Exception e) {
            return false;
        } 
    }
 
}

자바에서는 빈을 선언할 때 이 사용자 정의 조건 클래스를 사용할 수 있다.


@Conditional(JdbcTemplateCondition.class)
@Bean
public MyService myService() {

}

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.