19.스프링으로 aop구현하기
스프링으로 AOP를 구현하기
- 프락시 클래스에 구현되는 Cross-cutting Concern
스프링은 AOP을 4가지로 구분
Before:앞에만 필요한 AOP
After returnning: 뒤에만 필요한 AOP
After throwing: 예외처리할떄 필요한 AOP
Around: 모두 필요한 AOP - Advice(타겟에 제공할 부가기능을 가진다)
- Around 사용해보기
<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" />
<!-- 핸들러 넣어준다 -->
<property name="interceptorNames">
<list>
<value>logAroundAdvice</value>
</list>
</property>
</bean>
따로 프락시 클래스를 만들어 생성한다
public class LogAroundAdvice implements MethodInterceptor {
// 외부적인 요소와 연관 되지 않게 해결한다
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
long start = System.currentTimeMillis();
Object result = invocation.proceed();
long end = System.currentTimeMillis();
String massage = (end - start) + "ms 시간 걸렸습니다";
System.out.println(massage);
return result;
}
}
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 %f\n", proxy.avg());
exam으로 바꿔서 사용해볼 수도 있다
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring/aop/setting.xml");
Exam exam = (Exam) context.getBean("exam");
System.out.printf("total is %d\n", exam.total());
System.out.printf("avg is %f\n", exam.avg());
<bean id ="exam" class ="spring.aop.entity.NewlecExam" p:kor="1" p:eng="1" p:math="1" p:com="1"/>
total is 4
avg is 1.000000
댓글남기기