본문 바로가기

Back-End/Java

[Spring] AOP

AOP를 사용하기 위해 pom.xml에 아래 코드를 추가해야 합니다.


pom.xml

Spring AOP(4.3.13)

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>4.3.13.RELEASE</version>
</dependency>
cs


AspectJ Weaver(1.8.13)

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.13</version>
</dependency>
cs




AdviceLog.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Aspect //AOP에 관련된 작업을 하는 Class
public class AdviceLog {
    private static final Logger logger = LoggerFactory.getLogger(AdviceLog.class);
    
    //정상적으로 실행되어야 될 비즈니스 로직 메소드
    @Around("within(com.example.spring..*)"//실행할 위치(spring package 하부 모든 함수)
    public Object processTimeCheck(ProceedingJoinPoint proceedingJoinPoint) {
    
        String name = proceedingJoinPoint.getSignature().toLongString();
        logger.debug(name+" is start>>>");
        long startTime = System.currentTimeMillis();
        
        Object obj = null;
        try {
            obj = proceedingJoinPoint.proceed(); //실행되어져야 할 함수 호출
        } catch (Throwable e) {
            e.printStackTrace();
        }finally {
            long endTime = System.currentTimeMillis();
            logger.debug(name+" is finish>>>");
            logger.debug(name + " 실행경과시간 : " + (endTime-startTime));
        }
        
        return obj;
    }
}
cs




servlet-context.xml


네임스페이스에서 aop를 체크합니다.


1
2
3
4
5
6
7
8
9
10
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
</beans:beans>
cs


그러면 5번째줄에 aop관련 코드가 추가됩니다.


1
2
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<beans:bean id="adviceLog" class="com.example.spring.common.aop.AdviceLog"></beans:bean>
cs


내용



실행결과


com.example.spring의 하부에 있는 모든 함수들이 실행될때마다 로그가 기록됩니다.