Spring

[Spring] AOP 구현 - Annotation

📝 작성 : 2020.07.09  ⏱ 수정 : 
728x90

지난 시간에는 AOP를 xml 스키마 기반으로 구현해봤습니다. 이번에는 @Aspect 어노테이션을 통해 구현해보도록 하겠습니다.
전의 소스를 대부분 재활용 했습니다.

public interface Attendance {
    public void Attendance(String name);
}

public class Student implements Attendance {
    @Override
    public void Attendance(String name) {
        System.out.println(name + " 출석");
    }
}

public class Teacher implements Attendance {
    @Override
    public void Attendance (String name) {
        System.out.println(name + " 출근");
    }
}

@Aspect
public class AttendanceTime {
    @Pointcut("execution(* chap06_AOP.byAnnotation..*(..))")
    private void targetPoint(){}

    @Around("targetPoint()")
    public Object time(ProceedingJoinPoint joinPoint) throws Throwable {
        String sigature = joinPoint.getSignature().getName();
        System.out.println(sigature + " 시작!");
        LocalTime now = LocalTime.of(7, 55);
        System.out.printf("출발 시간 : %s\n", now);
        try {
            Object result = joinPoint.proceed();
            return result;
        } finally {
            Signature sig = joinPoint.getSignature();
            System.out.printf("도착 시간 :  %s\n", now.plusMinutes(10));
            System.out.println(sigature + " 끝!");
        }
    }
}

클래스 이름위에 @Aspect를 붙입니다. @Pointcut 어노테이션을 이용하여 Pointcut을 설정해줍니다.(뒤의 execution 관련해서는 스프링 공식문서에서 자세하게 살펴보실 수 있습니다.)

실제 기능을 수행할 메서드 위에 @Around(또는 @Before, @After 등) 어노테이션, 그리고 @Pointcut 어노테이션을 붙인 메서드 명을 같이 써줍니다.

<aop:aspectj-autoproxy/>

<bean id="timer" class="chap06_AOP.byAnnotation.AttendanceTime"/>

<bean id="student" class="chap06_AOP.byAnnotation.Student"/>
<bean id="teacher" class="chap06_AOP.byAnnotation.Teacher"/>

@Aspect 어노테이션을 사용하기 위한 <aop:aspectj-autoproxy/> 설정을 합니다.

public class Main {
    public static void main(String[] args) {
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:aopAspect.xml");

        Attendance student = ctx.getBean("student", Attendance.class);
        student.Attendance("홍길동");

        Attendance teacher = ctx.getBean("teacher", Attendance.class);
        teacher.Attendance("김길동");
    }
}

결과
Attendance 시작!
출발 시간 : 07:55
홍길동 출석
도착 시간 :  08:05
Attendance 끝!
Attendance 시작!
출발 시간 : 07:55
김길동 출근
도착 시간 :  08:05
Attendance 끝!

반응형

'Spring' 카테고리의 다른 글

[Spring] Spring Framework뼈대  (0) 2020.07.17
[Spring] IoC  (0) 2020.07.10
[Spring] ORM, JPA, Hibernate, Spring Data JPA의 개념  (0) 2020.07.08
[Spring] AOP 구현 (XML)  (0) 2020.07.06
[Spring] AOP의 개념  (0) 2020.07.06