본문 바로가기

프레임워크/Spring

[프레임워크] <Spring>〈Maven〉AOP 관심 분리

관심 분리(Separation of concerns)

비즈니스 메서드(비즈니스 로직, 핵심 관심, CRUD)에서 횡단 관심(공통 로직)을 분리하는 것이다.

◎ 로직(관심)들끼리 코드를 관리한다.

   ⇨ 높은 응집도를 보장한다.


AOP를 활용하기 위한 applicationContext.xml 스키마

◎ xmlns:aop="http://www.springframework.org/schema/aop"

http://www.springframework.org/schema/aop 

http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"

<?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
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-4.2.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">

</beans>

공통 로직(횡단 관심)

  인증 로깅 보안 트랜잭션 예외처리
C O O X O O
R X O X X X
U O O O O O
D O O O O O

 


@Autowired를 이용한 분리

◎ Advice 클래스로 분리한다.

public class LogAdvice {
	public void printLog() {
		System.out.println("로그 01 비즈니스 메서드 수행전해 수행되는 로그");	
	}
}

 

◎ Advice를 Service의 멤버변수로 설정한다.

   ⇨ 의존 관계

<bean class="com.spring.biz.common.LogAdvice" id="logAdvice" />
@Service("boardService")
public class BoardServiceImpl implements BoardService {
	@Autowired
	private BoardDAO bDAO;
	@Autowired
	private LogAdvice logAdvice;    
}

 

◎ 비즈니스 로직 수행 전에 호출한다.

@Service("boardService")
public class BoardServiceImpl implements BoardService {
	@Autowired
	private BoardDAO bDAO;
    
	@Autowired
	private LogAdvice logAdvice;
	
	@Override
	public ArrayList<BoardDTO> selectAll(BoardDTO bDTO) {
		// TODO Auto-generated method stub
		logAdvice.printLog();
		return bDAO.selectAll(bDTO);
	}
}

pointcut과 aspect를 활용한 분리

◎ joinpoint

   ⇨ 어플리케이션에 존재하는 모든 비즈니스 메서드

   ⇨ aspect와 결합하면 포인트 컷이라고 부른다. 

◎ pointcut

   횡단 관심을 연결할 비즈니스 메서드

◎ aspect

   포인트컷(핵심로직)과 어드바이스(횡단관심)의 조합

  ⇨ 포인트컷과 어드바이스의 결합(위빙)

<context:component-scan base-package="com.spring.biz" />

//  LogAdvice 클래스를 빈으로 등록
<bean class="com.spring.biz.common.LogAdvice" id="logAdvice" />

// AOP 구성을 정의하는 태그
<aop:config>
	// aPointcut이라는 아이디로 Pointcut을 정의
    // com.spring.biz 패키지 또는 하위 패키지에 있는 모든 *Impl로 끝나는 클래스의 모든 메소드에 해당
	<aop:pointcut id="aPointcut" expression="execution(* com.spring.biz..*Impl.*(..))" />
    
    // bPointcut이라는 아이디로 또 다른 Pointcut을 정의 
    // com.spring.biz 패키지 또는 하위 패키지에 있는 모든 *Impl로 끝나는 클래스 중에서 select로 시작하는 메소드에 해당
    <aop:pointcut id="bPointcut" expression="execution(* com.spring.biz..*Impl.select*(..))" />
    
    // logAdvice 빈을 참조하며, LogAdvice 클래스에 정의된 Advice를 적용
    <aop:aspect ref="logAdvice">
    	// aPointcut에 정의된 지점에서 Advice를 적용
   		<aop:before pointcut-ref="aPointcut" method="printLog" />
   	</aop:aspect>
</aop:config>