본문 바로가기
스프링

AOP 관점 지향 프로그래밍

by y00ns00 2020. 5. 20.

AOP(Aspect Oriented Programming) - 관점 지향 프로그래밍

( OOP를 더 잘 구현할 수 있도록 도와주는 프로그램 )

여러 객체에 공통적으로 적용할 수 있는 기능을 분리함으로써 재사용을 높여주는 프로그래밍 기법

  - 사용 : 원래 업무들에서 공통된 업무들을 찾고 그 업무들을 AOP로 만들어 놓고

            필요로 한 순 간에 사이사이로 끼워 넣기

AOP 종류

 - before : 메소드 실행 전 실행

 - after-returning : 메소드 실행 후 실행

 - after-throwing : 메소드 실행 중 예외 발생시

 - after : 메소드 실행 후 실행(예외 발생 여부 상관 없음)

 - around : 메소드 실행 전/후, 예외 발생 시 실행 

 

AOP 지원

     1) AspectJ  :   1) 코드 적용

                        2) Complie 시 적용

 

     2) spring       3) Runtime시 적용 (proxy 사용)

 

 

 

실습(before)

 

 

의존성 주입

 

	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-context</artifactId>
	    <version>5.2.6.RELEASE</version>
	</dependency>

 

상속받기위한 수행기능 인터페이스

package spring_aop01_before;

public interface CustomerService {
	public void printName();
	public void printEmail();
	
}

 

기능 상속받아 구현할 클래스

package spring_aop01_before;

public class CustomerServiceImple implements CustomerService{
	
	String name;
	String email;
	
	
	public void setName(String name) {
		this.name = name;
	}
	
	public void setEmail(String email) {
		this.email = email;
	}
	
	
	
	
	
	@Override
	public void printName() {
		// TODO Auto-generated method stub
		System.out.println("이름 : "+ name);
		
	}
	@Override
	public void printEmail() {
		// TODO Auto-generated method stub
		System.out.println("이메일 :"+ email);
		
	}
	
	
}

 

 

끼어들 작업

MethodBeforeAdvie을 오버라이딩 하여 사용하여

 

지정한 타겟이 실행되기 전에 실행되도록 구현

package spring_aop01_before;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

// 이 객체를 메인업무 호출 전에 실행하고 싶음 
public class HijackAdvice implements MethodBeforeAdvice{

	@Override
	public void before(Method method, Object[] args, Object target) throws Throwable {
		// advice 원하는 타이밍에 실행되야할 코드 
		System.out.println("공통된 관심업무를 지정 ");
		System.out.println("메인업무가 실행되기 전에 가로채기");
		
	}
	
}

 

 

스프링 설정 

끼어들 bean을 호출

실행할 작업 호출

타겟과 끼어넣을 작업을 proxy에 지정

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

<bean id="hijack" class="spring_aop01_before.HijackAdvice">
	
</bean>



<bean id="biz" class="spring_aop01_before.CustomerServiceImple">
	<property name="name" value="홍길동" />	
	<property name="email" value="hong@gmail.com" />
</bean>

<bean id="execute" class="org.springframework.aop.framework.ProxyFactoryBean">
	<!-- 대행자에게(proxy)에게 biz를 타겟으로 지정 -->
	<property name="target" ref="biz" />
	
	<!-- aspect(측면)에서 끼워넣을 작업(advice)를 지정 -->
	<property name="interceptorNames">
		<value>hijack</value>
	
	</property>
	
	
</bean>


	
	
	
</beans>

 

실행할 메인 class

 

 

package spring_aop01_before;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class TestMain {
	public static void main(String[] args) {
		
		ApplicationContext context =
				new GenericXmlApplicationContext("app.xml");
		
		CustomerService cs = context.getBean("execute",CustomerService.class);
		
		cs.printName();
		cs.printEmail();
		
		
		
	}
}

 

실행시 타겟이 실행되기전에 끼어들도록 지정한 hijack기능이 끼어들게된다.

 

 

 

 

AspectJ 용어

 - Target : 실질적인 비지니스 로직을 구현하는 코드

 - JointPoint : 메소드 호출하는 시점

 - PointCut : 여러 개의 JointPoint를 하나로 결합한 것

               : Target 클래스에 advice가 결합된 때 둘사이의 결합규칙을 정의한 것

      + expression

            '*' : 모든값

            '..' : 0개 이상

 ex) execution(public void set*(..)) : void형이 이름이 set으로 시작하고, 파라미터가0개 이상인 메소드 호출

      execution(* get*(*) ) : 이름이 get으로 시작하고 1개의 파라미터를 갖는 메소드 호출 

      execution(* get(*,*) ) : 이름이 get으로 시작하고 2개의 파라미터를 갖는 메소드 호출

 

 - Advice : JointPoint 에서 실행되어야 하는 코드

               ex) (횡단관심사) 트랜잭션, 로그, 보안,인증

 - weaving : advice를 핵심 코드에 삽입하는 것

 

 

준비

AspectJ Weaver

 

Maven Repository: org.aspectj » aspectjweaver

The AspectJ weaver introduces advices to java classes VersionRepositoryUsagesDate1.9.x1.9.5Central456Nov, 20191.9.4Central503May, 20191.9.3Central371Apr, 20191.9.3.RC1Central1Mar, 20191.9.2Central506Oct, 20181.9.1Central376Apr, 20181.9.0Central6Apr, 20181.

mvnrepository.com

AspectJ Runtime

 

Maven Repository: org.aspectj » aspectjrt

The runtime needed to execute a program using AspectJ VersionRepositoryUsagesDate1.9.x1.9.5Central425Nov, 20191.9.4Central469May, 20191.9.3Central372Apr, 20191.9.3.RC1Central1Mar, 20191.9.2Central512Oct, 20181.9.1Central408Apr, 20181.9.0Central20Apr, 20181

mvnrepository.com

 

 

 

 

 

 

 

 

 

 

 

'스프링' 카테고리의 다른 글

@ResponseBody  (0) 2020.06.04
spring websocket + stomp  (0) 2020.06.03
자바 jdbc 스프링 DB 접근  (0) 2020.05.19
annotation  (0) 2020.05.18
maven  (0) 2020.05.18

댓글