xml을 이용해서 aop설정을 할 수 있습니다. 우선 spring.io의 xml을 참고해서 넣어준 뒤, maven에 의존성을 추가해줍니다. 그리고 우선 bean을 만들어주고, aspect를 만들고 만든 bean의 ref를 추가합니다. 마지막으로 그 안에 pointcut 정의, advice 정의를 해줍니다.
pointcut 문법
execution -> 런타임시 실행
* -> 모든 클래스, 모든 메서드
(..) -> 모든 argument
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<aop:config>
<aop:aspect id="myAspect" ref="aBean">
<aop:pointcut id="businessService"
expression="execution(* kr.co.fast.cli.aop.Service.*(..))"/> <!-- point cut 정의 -->
<aop:around pointcut-ref="businessService" method="aroundLog" />
<!-- <aop:before pointcut-ref="businessService" method="beforeLog" /> beforeAdvice 정의
<aop:after pointcut-ref="businessService" method="afterLog" /> afterAdvice 정의(무조건 로직 실행후 실행)
<aop:after-returning pointcut-ref="businessService" method="afterReturningLog" /> afterReturningAdvice(로직이 잘 실행되면 그 후 실행) 정의
<aop:after-throwing pointcut-ref="businessService" method="afterThrowingLog" /> afterThrowingAdvice(로직이 예외발생시 실행) 정의 -->
</aop:aspect>
</aop:config>
<bean id="aBean" class="kr.co.fast.cli.aop.AopBean">
</bean>
<bean id="service" class="kr.co.fast.cli.aop.Service">
</bean>
</beans>
package kr.co.fast.cli.aop;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Service {
public void log() {
log.error(">>>> aop log");
}
}
package kr.co.fast.cli.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
@Slf4j
public class AopBean {
public void beforeLog() {
System.out.println(">>>> before AOP Log!");
}
public void afterLog() {
System.out.println(">>>> after AOP Log!");
}
public void afterReturningLog() {
System.out.println(">>>> afterReturning AOP Log!");
}
public void afterThrowingLog() {
System.out.println(">>>> afterThrowing AOP Log!");
}
public void aroundLog(ProceedingJoinPoint pjp) { // around는 ProceedingJoinPoint 필요! -> 이것 사용시 위에 것 모두 대체 가능!
log.error(">>>> before AOP Log!");
try {
Object proceed = pjp.proceed();
log.error(">>>> returning AOP Log!");
} catch (Throwable throwable) {
log.error(">>>> throwing AOP Log!");
}
log.error(">>>> after AOP Log!");
}
}
package kr.co.fast.cli.aop;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
Service service = context.getBean(Service.class);
service.log();
context.close();
}
}