14. AOP(3)

Seungjae·2021년 2월 13일
0

Spring 다지기

목록 보기
14/14

AOP(3)


AOP를 이용해서 계속해서 반복되는 로직을 처리할 수 있습니다. 가장 적절한 예시는 transaction 처리입니다. 일반적인 transaction처리를 살펴보겠습니다.

connection.setAutoCommit(false);
try {
    statement.executeUpdate("insert into member(username, password) values('oh980225', '1234')");
    connection.commit();
} catch (SQLException e) {
    connection.rollback();
}

이 코드는 transaction 처리를 사용하는 모든 로직에 붙어있게 될 것입니다. 하지만 aop를 사용하면 더욱 간단히 해결할 수 있습니다.

public Object aroundTransaction(ProceedingJoinPoint pjp) throws SQLException {
        log.error(">>>> before AOP Transaction  Log!");
        connection.setAutoCommit(false);
        try {
            Object proceed = pjp.proceed();
            log.error(">>>> commit!");
            connection.commit();

            return proceed;
        } catch (Throwable throwable) {
            log.error(">>>> rollback!");
            connection.rollback();
        }
        log.error(">>>> after AOP  Log!");
        return null;
}

위 처럼 aop로 처리를 해줄 경우 기존 코드가 매우 간결해집니다.

statement.executeUpdate("insert into member(username, password) values('oh980225', '1234')");

AOP를 어노테이션을 이용해서 사용하기


자바 설정 파일(@Configuration)에 @EnableAspectJAutoProxy를 추가하여 사용할 수 있습니다. 그리고 기존 AOP로직을 수행하던 클래스에 @Aspect을 추가해줍니다. 또한 @Pointcut을 사용해서 Poincut을 설정해줄 수도 있습니다. 어드바이스도 물론 @Around같은 어노테이션을 이용해서 만들 수 있습니다.

profile
코드 품질의 중요성을 아는 개발자 👋🏻

0개의 댓글