스프링 AOP실습, 선언적방식(XML방식),ProxyFactoryBean,AspectJExpressionPointcut실습(자…

스프링 AOP실습,선언적방식(XML방식),ProxyFactoryBean,AspectJExpressionPointcut실습(자바동영상/스프링동영상/자바교육/스프링교육/스프링프레임워크/스프링학원/자바학원/자바/JAVA)   

 

 

ProxyFactoryBean, AspectJExpressionPointcut 이용한 선언적 AOP 구현(XML 기반) 실습

 

n  프로그래밍적인 방법(소스코드를 통한 Advice, Advisor, Pointcut, Proxy작성)을 통해 구현한 이전 SmallMart 예제를 ProxyFactoryBean, AspectJExpressionPointcut을 이용하여 XML을 이용한 방식으로 구현해 보자. (Pointcut을 사용하여 getProducts2() 메소드만 충고를 받을 수 있도록 구현)

n  먼저 이전 예제를 살펴보자.

 

 

1. SmallMart.java

 

package onj.hello.aop;

 

public interface SmallMart {

           public String getProducts(String productName) throws Exception ;

           public String getProducts2(String productName) throws Exception ;

}

 

 

 

2. SmallMartImpl.java

 

package onj.hello.aop;

 

public class SmallMartImpl implements SmallMart{

           public String getProducts(String productName) throws Exception {

                      System.out.println("getProduct()…" + productName);

                      //throw new Exception("예외 발생 시킴...");

                      return "SmallMart  getProducts......................";

           }

          

           public String getProducts2(String productName) throws Exception {

                      System.out.println("getProduct2()…" + productName);

                      //throw new Exception("예외 발생 시킴...");

                      return "SmallMart  getProducts2().....................";

           }

}

 

 

3. 이번에는 충고 클래스를 각각 만들자.

 

 

package oraclejava.traing.aop2;

 

import java.lang.reflect.Method;

 

import org.springframework.aop.AfterReturningAdvice;

 

public class AfterLoggingAdvice implements AfterReturningAdvice{

           public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable{

                      System.out.println(arg1.getName() + " : 사후충고");

           }

}

 

 

 

 

 

package oraclejava.traing.aop2;

 

import org.aopalliance.intercept.MethodInterceptor;

import org.aopalliance.intercept.MethodInvocation;

 

public class AroundLoggingAdvice implements MethodInterceptor {

           public Object invoke(MethodInvocation arg0) throws Throwable {

                      String findName = (String) arg0.getArguments()[0];

                      if (findName == null) {

                                 throw new Throwable("예외");

                      }

                      System.out.println("[주변충고]메소드실행전..");

                      Object returnedObj = arg0.proceed();

                      System.out.println("[주변충고]메소드실행후");

                      //주변충고는 원래 메소드의 리컨값을 대체할 수 있다.

                      return "[주변충고]getProducts2() 메소드의 리턴을 대체 한것입니다.";

           }// :

}

 

 

 

 

package oraclejava.traing.aop2;

 

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

 

public class BeforeLoggingAdvice implements MethodBeforeAdvice{

           public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable{//대상메소드의첫번째인자를캐스팅(String productName) …

                      String findName= (String)arg1[0];

                      System.out.println(arg0.getName() + ":: 사전충고.");

           }

}

 

 

 

 

 

package oraclejava.traing.aop2;

 

import org.springframework.aop.ThrowsAdvice;

 

public class ThrowsLoggingAdvice implements ThrowsAdvice{

           public void afterThrowing(Throwable throwable) {

                      System.out.println("예외충고 ....");

           }

}

 

 

4. 이번에는 포인트컷을 만들자. StaticMethodMatcherPointcut은 클래스이름 or 메소드 이름과 같은 정적인 정보에 기초하여 출고를 받을 메소드를 정의하는 포인트컷이며 스프링에서 제공한다. 이를 상속받아 포인트컷 클래스를 작성하자.

 

SmallMart클래스의 getProducts2 메소드가 충고를 받을 메소드 이다.

 

package oraclejava.traing.aop2;

 

import java.lang.reflect.Method;

 

import org.springframework.aop.ClassFilter;

import org.springframework.aop.support.StaticMethodMatcherPointcut;

 

public class SmallMartStaticPointcut extends StaticMethodMatcherPointcut{

           public boolean matches(Method method, Class<?> cls) {

                      return ("getProducts2".equals(method.getName()));

           }

      //아래처럼 getClassFilter를 만들어도 되지만 위 matches return문에 clas파라미터를

     //이용하여 같이 클래스 이름도 비교하면 더 간단해 진다.

     //return ("getProducts2".equals(method.getName() && cls == SmallMartImpl.class));

           public ClassFilter getClassFilter() {

                      return new ClassFilter() {

                                 public boolean matches(Class<?> cls) {

                                             return(cls== SmallMartImpl.class);}};}

}

 

 

 

5. 메인클래스

 

 

package onj.hello.aop;

 

import org.aopalliance.aop.Advice;

import org.springframework.aop.Advisor;

import org.springframework.aop.Pointcut;

import org.springframework.aop.framework.ProxyFactory;

import org.springframework.aop.support.DefaultPointcutAdvisor;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

 

@SpringBootApplication

public class DemoSmallmart1Application {

 

           public static void main(String[] args) {

                      SpringApplication.run(DemoSmallmart1Application.class, args);

                     

                      SmallMart target = new SmallMartImpl();

                     

                      Pointcut pc = new SmallMartStaticPointcut();

 

                      Advice advice1= new AfterLoggingAdvice();

                      Advisor advisor1= new DefaultPointcutAdvisor(pc, advice1);

                     

                      Advice advice2= new BeforeLoggingAdvice();

                      Advisor advisor2= new DefaultPointcutAdvisor(pc, advice2);

                     

                      Advice advice3= new AroundLoggingAdvice();

                      Advisor advisor3= new DefaultPointcutAdvisor(pc, advice3);

                     

                      Advice advice4= new ThrowsLoggingAdvice();

                      Advisor advisor4= new DefaultPointcutAdvisor(pc, advice4);

                     

                      ProxyFactory pf = new ProxyFactory();

                                            

                      pf.addAdvisor(advisor1);

                      pf.addAdvisor(advisor2);

                      pf.addAdvisor(advisor3);

                      pf.addAdvisor(advisor4);

                     

                      pf.setTarget(target);

                     

                      try {

                                 SmallMart proxy = (SmallMart) pf.getProxy();

                                 System.out.println(proxy.getProducts("오라클자바커뮤니티"));

                                 System.out.println(proxy.getProducts2("오라클자바커뮤니티"));

                      } catch (Exception e) {

                                 e.printStackTrace(System.out);

                      }

           }

 

}

 

 

n  XML 기반으로 선언적으로

 

STS에서

 

1. File -> New -> Maven Project

다음페이지 create simple project 체크 후 NEXT

실습편의상 Project name/Artifact-ID/Name/Description 모두 동일하게 : demo-smallmart1 로 설정

 

 

[pom.xml]

<project xmlns="http://maven.apache.org/POM/4.0.0"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

       <modelVersion>4.0.0</modelVersion>

       <groupId>aoptest</groupId>

       <artifactId>aoptest</artifactId>

       <version>0.0.1-SNAPSHOT</version>

       <name>aoptest</name>

       <description>aoptest</description>

 

       <properties>

             <org.springframework-version>5.2.9.RELEASE</org.springframework-version>

             <aspectj-version>1.9.6</aspectj-version>

       </properties>

 

       <dependencies>

             <dependency>

                    <groupId>org.springframework</groupId>

                    <artifactId>spring-context</artifactId>

                    <version>${org.springframework-version}</version>

             </dependency>

 

             <dependency>

                    <groupId>org.aspectj</groupId>

                    <artifactId>aspectjweaver</artifactId>

                    <version>${aspectj-version}</version>

             </dependency>

 

             <dependency>

                    <groupId>org.aspectj</groupId>

                    <artifactId>aspectjrt</artifactId>

                    <version>${aspectj-version}</version>

             </dependency>

 

       </dependencies>

 

</project>

 

[SmallMart.java]

package onj.hello.aop1;

 

public interface SmallMart {

           public void getProducts(String productName) throws Exception;

           public void getProducts2(String productName) throws Exception;

}

 

[SmallMartImpl.java]

 

package onj.hello.aop1;

 

public class SmallMartImpl implements SmallMart{

public void getProducts(String productName) throws Exception{

System.out.println("getProduct()..." + productName);

throw new Exception("error");

}

 

public void getProducts2(String productName) throws Exception{

System.out.println("getProduct2()..." + productName);

throw new Exception("error");

}

}

 

[BeforeLoggingAdvice.java]

package onj.hello.aop1;

 

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

 

public class BeforeLoggingAdvice implements MethodBeforeAdvice{

public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable{

String findName = (String)arg1[0];

System.out.println(arg0.getName() + ";;사전충고");

}

}

 

[AfterLoggingAdvice.java]

package onj.hello.aop1;

 

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

 

public class AfterLoggingAdvice implements AfterReturningAdvice{

public void afterReturning(Object arg0, Method arg1, Object[] arg2,Object arg3)

throws Throwable{

System.out.println(arg1.getName() +  ": 사후충고");

}

}

 

[AroundLoggingAdvice.java]

package onj.hello.aop1;

 

import org.aopalliance.intercept.MethodInterceptor;

import org.aopalliance.intercept.MethodInvocation;

 

public class AroundLoggingAdvice implements MethodInterceptor{

public Object invoke(MethodInvocation arg0) throws Throwable{

String findName= (String)arg0.getArguments()[0];

if(findName== null) {

throw new Throwable("예외");

}

System.out.println("메소드실행전");

Object returnedObj= arg0.proceed();

System.out.println("메소드실행후");

return returnedObj;

}

}

 

[ThrowsLoggingAdvice.java]

package onj.hello.aop1;

 

import org.springframework.aop.ThrowsAdvice;

 

public class ThrowsLoggingAdvice implements ThrowsAdvice{

public void afterThrowing(Throwable throwable){

System.out.println("예외충고 발생...");

}

}

 

[SmallMartApp.java]

package onj.hello.aop1;

 

import org.springframework.aop.framework.ProxyFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

public class SmallMartApp {

public static void main(String[] args) throws Exception{

ApplicationContext ctx = new ClassPathXmlApplicationContext(“smallmart1.xml”);

 

SmallMart smallMart = (SmallMart)ctx.getBean("smallMartProxy");

 

smallMart.getProducts("과자");

smallMart.getProducts2("과일");

}

}

 

[/src/main/resources/smallmart1.xml]

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

 

       <!-- target -->

       <bean id="smallMart" class="onj.hello.aop1.SmallMartImpl" />

      

       <!-- pointcut -->

       <bean id="myPointcut"    class="org.springframework.aop.aspectj.AspectJExpressionPointcut">

             <property name="expression">

                    <value>execution(* getProducts2*(..))</value>

             </property>

       </bean>

 

       <!-- advice -->

       <bean id="beforeAdvice" class="onj.hello.aop1.BeforeLoggingAdvice" />

       <bean id="afterAdvice" class="onj.hello.aop1.AfterLoggingAdvice" />

       <bean id="aroundAdvice" class="onj.hello.aop1.AroundLoggingAdvice" />

       <bean id="throwsAdvice" class="onj.hello.aop1.ThrowsLoggingAdvice" />

      

       <bean id="smallMartAdvisor1" class="org.springframework.aop.support.DefaultPointcutAdvisor">

             <property name="advice">

                    <ref bean="beforeAdvice"></ref>

             </property>

             <property name="pointcut">

                    <ref bean="myPointcut"/>

             </property>

       </bean>

      

       <bean id="smallMartAdvisor2" class="org.springframework.aop.support.DefaultPointcutAdvisor">

             <property name="advice">

                    <ref bean="afterAdvice"></ref>

             </property>

             <property name="pointcut">

                    <ref bean="myPointcut"/>

             </property>

       </bean>

      

       <bean id="smallMartAdvisor3" class="org.springframework.aop.support.DefaultPointcutAdvisor">

             <property name="advice">

                    <ref bean="aroundAdvice"></ref>

             </property>

             <property name="pointcut">

                    <ref bean="myPointcut"/>

             </property>

       </bean>

      

       <bean id="smallMartAdvisor4" class="org.springframework.aop.support.DefaultPointcutAdvisor">

             <property name="advice">

                    <ref bean="throwsAdvice"></ref>

             </property>

             <property name="pointcut">

                    <ref bean="myPointcut"/>

             </property>

       </bean>

      

       <bean id="smallMartProxy" class="org.springframework.aop.framework.ProxyFactoryBean">

             <property name="target">

                    <ref bean="smallMart" />

             </property>

             <property name="interceptorNames">

                    <list>

                           <value>smallMartAdvisor1</value>

                           <value>smallMartAdvisor2</value>

                           <value>smallMartAdvisor3</value>

                           <value>smallMartAdvisor4</value>

                    </list>

             </property>

       </bean>

 

</beans>

 

[실행결과]

getProduct()...과자

getProducts2;;사전충고

메소드실행전

getProduct2()...과일

메소드실행후

getProducts2: 사후충고

 

[실행결과]

getProduct()...과자

getProducts2;;사전충고

메소드실행전

getProduct2()...과일

예외충고 발생...

Exception in thread "main" java.lang.Exception: error

       at onj.hello.aop1.SmallMartImpl.getProducts2(SmallMartImpl.java:11)

       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

       at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

       at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

       at java.lang.reflect.Method.invoke(Unknown Source)

       at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)

       at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)

       at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)

       at org.springframework.aop.framework.adapter.ThrowsAdviceInterceptor.invoke(ThrowsAdviceInterceptor.java:112)

       at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)

       at onj.hello.aop1.AroundLoggingAdvice.invoke(AroundLoggingAdvice.java:13)

       at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)

       at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:55)

       at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)

       at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:56)

       at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)

       at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)

       at com.sun.proxy.$Proxy4.getProducts2(Unknown Source)

       at onj.hello.aop1.SmallMartApp.main(SmallMartApp.java:14)

 

 

 

 

#ProxyFactoryBean, #AspectJExpressionPointcut, #스프링포인트컷, #스프링충고, #포인트컷, #스프링pointcut, #스프링AOP, #스프링advice, #SpringAOP, #스프링DI, #스프링IoC, #SpringDI, #SpringIoC, #자바스프링, #Spring동영상, #Spring강의, #스프링프레임워크, #스프링교육, #스프링학원, #스프링강좌, #스프링강의, #자바학원, #자바, #스프링동영상, #자바동영상, #스프링프레임워크교육, #스프링프레임워크강의, #스프링프레임워크학원  

, , , , , , , , , , , , , , , , , , , , , , , ,

Comments