Spring

[Spring] AOP 구현 (XML)

📝 작성 : 2020.07.06  ⏱ 수정 : 
728x90

AOP 구현

스프링 AOP를 구현하는 방법에는 두가지가 있습니다.

  1. XML 스키마 기반의 자바 POJO 클래스를 이용하여 구현
  2. @Aspect 어노테이션 이용하여 구현

POJO(Plain Old Java Object)
순수한 자바 객체를 의미합니다. 즉, 특정 기술에 종속적이지 않은 자바 객체라는 의미입니다.

XML과 어노테이션을 이용해 구현한다는 차이점이 있지만 두 방법 모두 큰 틀은 같습니다.

  1. 공통 기능을 제공하는 Aspect를 구현
  2. Aspect를 어디에(PointCut) 적용할지 설정 즉, Advice를 설정

의존 설정

Maven

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.2</version>
</dependency>

Gradle

compile group: 'org.aspectj', name: 'aspectjweaver', version: '1.9.2'

버전은 편하신 버전을 선택하시면 되겠습니다.

XML 스키마 기반으로 AOP 구현

학생과 선생님의 출석, 출근 시간을 나타내는 프로그램을 작성해보겠습니다.

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

 

출석, 출근 시간을 구하는 Aspect를 구현합니다.

public class AttendanceTime {
    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 + " 끝!");
        }
    }
}

 

XML 스키마를 이용하여 Aspect를 설정합니다.

<bean id="attendanceTime" class="my.dhlee.aop.AttendanceTime"/>

<aop:config>
  <aop:aspect id="timer" ref="attendanceTime">
    <aop:pointcut id="publicMethod" expression="within(my.dhlee.aop.*)"/>
    <aop:around method="time" pointcut-ref="publicMethod" />
  </aop:aspect>
</aop:config>

<bean id="student" class="my.dhlee.aop.Student"/>
<bean id="teacher" class="my.dhlee.aop.Teacher"/>

 

프로그램을 실행할 메인 클래스를 작성합니다.

public class Main {
    public static void main(String[] args) {
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:aopPOJO.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 끝!

 

실행순서가 `공통기능 => 핵심기능(try) => 공통기능(finally)`이렇게 됩니다.
다음에는 @Aspect 어노테이션을 이용해 Aspect를 구현해보겠습니다.

반응형