๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ’ปStudy/Spring

Spring์œผ๋กœ AOP ๊ตฌํ˜„ (Around Advice)

 

๋ณด์กฐ ์—…๋ฌด์˜ ์‚ฌ์šฉ์— ๋”ฐ๋ผ ์Šคํ”„๋ง์€ Before Advice, After returnning Advice, After throwing Advice, Around Advice ๋„ค ๊ฐ€์ง€๋ฅผ ์ œ๊ณตํ•œ๋‹ค. ์ด์ „ ํฌ์ŠคํŒ…์—์„œ ์ˆœ์ˆ˜ ์ž๋ฐ”๋กœ๋งŒ AOP๋ฅผ ๊ตฌํ˜„ํ–ˆ๋˜ ์ฝ”๋“œ๋ฅผ ์ˆ˜์ •ํ•˜์—ฌ Around Advice๋ฅผ ๊ตฌํ˜„ํ•ด ๋ณด๋„๋ก ํ•˜๊ฒ ๋‹ค. (unounou.tistory.com/48)

 

 

Program.java

public class Program {

	public static void main(String[] args) {
		ApplicationContext context = 
				new ClassPathXmlApplicationContext("spring/aop/setting.xml");

		Exam proxy = (Exam) context.getBean("proxy");
		
		System.out.printf("total is %d\n", proxy.total());
		System.out.printf("avg is %d\n", proxy.total());
	}
}

 

LogAroundAdvice ํด๋ž˜์Šค๋ฅผ ์ƒ์„ฑํ•˜์—ฌ proxy๋ฅผ ๋”ฐ๋กœ ๋นผ๋†“๋Š”๋‹ค. invoke ๋ฉ”์†Œ๋“œ๊ฐ€ proxy์™€ ๊ฐ™๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค.

 

 

LogAroundAdvice.java

public class LogAroundAdvice implements MethodInterceptor{

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		
		/////////๋ณด์กฐ ์—…๋ฌด/////////
		long start = System.currentTimeMillis();
		/////////๋ณด์กฐ ์—…๋ฌด/////////
        
		//////////์ฃผ ์—…๋ฌด//////////
		Object result = invocation.proceed(); //proceed : invoke์™€ ๊ฐ™์€ ์—ญํ• 
		//////////์ฃผ ์—…๋ฌด//////////
        
		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
        
		/////////๋ณด์กฐ ์—…๋ฌด/////////		
		long end = System.currentTimeMillis();
		String message = (end - start) + "์‹œ๊ฐ„์ด ๊ฑธ๋ ธ์Šต๋‹ˆ๋‹ค.";
		System.out.println(message);
		/////////๋ณด์กฐ ์—…๋ฌด/////////
        
		return result;
	}
}

 

์Šคํ”„๋ง ์„ค์ •์„ ๋นผ๋†“๊ธฐ ์œ„ํ•ด setting.xml ํŒŒ์ผ์„ ์ถ”๊ฐ€ํ•œ๋‹ค.

 

setting.xml

<bean id="target" class="spring.aop.entity.NewlecExam"  p:kor="1" p:eng="1" p:math="1" p:com="1"/> 
<bean id="logAroundAdvice" class="spring.aop.advice.LogAroundAdvice"/>
<bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean"> 
   	<property name="target" ref="target"/> <!-- setTarget()์˜ ์˜๋ฏธ -->
   	<property name="interceptorNames">
   		<list>
   			<value>logAroundAdvice</value> <!-- ์ฐธ์กฐํ•˜๋Š” ๊ฐ์ฒด์˜ ์ด๋ฆ„ -->
   		</list>
   	</property>
</bean>

 


๋‰ด๋ ‰์ฒ˜ ์Šคํ”„๋ง ํ”„๋ ˆ์ž„์›Œํฌ ๊ฐ•์˜๋ฅผ ๋“ฃ๊ณ  ์ •๋ฆฌํ•œ ๊ฒŒ์‹œ๊ธ€์ž…๋‹ˆ๋‹ค.

www.youtube.com/user/newlec1