본문 바로가기

공부 자료/Spring

[Spring Core] AOP (Aspect Oriented Programming)

Spring 삼각형 -AOP

AOP(Aspect Oriented Programming)란?

: OOP(Object Oriented Programming)은 객체지향 프로그래밍 즉, 객체 간의 관계를 지향하는 프로그래밍 방식

: Aspect(관심)을 지향하는 프로그래밍은 애플리케이션에 필요한 기능 중에서 공통적으로 적용되는 공통 기능에 대한 관심과 연관됨

: 애플리케이션의 핵심 업무 로직에서 로깅이나 보안, 트랜잭션 같은 공통 기능 로직들을 분리하는 것

>> 관심 분리(Separation of Concerns)함으로서 재사용 가능한 모듈로서 사용할 수 있으며, 높은 응집도를 가짐 (SRT 하나의 책임)

 

* 공통 관심 사항(Cross-cutting concern)

: 애플리케이션 전반에 걸쳐 공통적으로 사용되는 기능들에 대한 관심사

: 핵심 관심 사항에 반대되는 개념으로서 '부가적인 관심 사항' 이라 표현하기도 함

 

* 핵심 관심 사항(Core concern)

: 비즈니스 로직 즉, 애플리케이션의 주목적을 달성하기 위한 핵심 로직에 대한 관심사

 

공통 기능 사용 이유

1) 코드의 간결성 유지

2) 객체 지향 설계 원칙에 맞는 코드 구현

3) 코드의 재사용

 

* 트랜잭션

: 데이터를 처리하는 하나의 작업 단위로 둘 다 성공해야 성공(커밋), 둘 중 하나라도 실패하면 실패(롤백)처리

커밋 : 모든 작업이 성공적으로 수행되었을 경우 수행한 작업을 DB에 반영하는 것

롤백 : 작업이 하나라도 실패한다면 이전에 성공한 작업들을 작업 수행 이전 상태로 되돌리는 것

 

//AOP 미적용 트랜잭션 예시
public class Main {
    private Connection connection;

    public void registerMember(Member member, Point point) throws SQLException {
        connection.setAutoCommit(false); // (1)
        try {
            saveMember(member); // (2)
            savePoint(point);   // (2)
            
            connection.commit(); // (3)
        } catch (SQLException e) {
            connection.rollback(); // (4)
        }
    }

    private void saveMember(Member member) throws SQLException {
        PreparedStatement psMember =
                connection.prepareStatement("INSERT INTO member (email, password) VALUES (?, ?)");
        psMember.setString(1, member.getEmail());
        psMember.setString(2, member.getPassword());
        psMember.executeUpdate();
    }

    private void savePoint(Point point) throws SQLException {
        PreparedStatement psPoint =
                connection.prepareStatement("INSERT INTO point (email, point) VALUES (?, ?)");
        psPoint.setString(1, point.getEmail());
        psPoint.setInt(2, point.getPoint());
        psPoint.executeUpdate();
    }
}

//AOP 적용 트랜잭션 예시
@Component
@Transactional // (1)
public class Main {
    private Connection connection;

    public void registerMember(Member member, Point point) throws SQLException {
        saveMember(member);
        savePoint(point);
    }

    private void saveMember(Member member) throws SQLException {
        // Spring JDBC를 이용한 회원 정보 저장
    }

    private void savePoint(Point point) throws SQLException {
        // Spring JDBC를 이용한 포인트 정보 저장
    }
}