English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
제공됩니다 Spring1.2오래된 AOP (DTD 기반) 구현 예제.
Spring에서는 3지원됩니다만, 다음 페이지에서 배울 예정인 Spring AOP와 AspectJ를 함께 사용하는 방법에 대해 조언을 사용합니다.
spring1.2ancient AOP 구현에서 지원됩니다.4종류의 Advice가 있습니다.
Before Advice실제 메서드 호출 전에 실행됩니다. After Advice실제 메서드 호출 후에 실행됩니다. 메서드가 반환 값을 가지면 반환 값 후에 실행됩니다. Around Advice실제 메서드 호출 전후에 실행됩니다. Throws Advice실제 메서드가 예외를 발생시키면 해당 Advice를 실행합니다.
다음 그래프를 통해 Advice 계층 구조를 이해해 보겠습니다:
모두 AOP에서의 인터페이스입니다.
MethodBeforeAdvice 인터페이스를 확장합니다. BeforeAdvice 인터페이스.
AfterReturningAdvice 인터페이스를 확장합니다. AfterAdvice 인터페이스.
ThrowsAdvice 인터페이스를 확장합니다. AfterAdvice 인터페이스.
MethodInterceptor 인터페이스를 확장합니다. Interceptor 인터페이스는 Advice 주위에서 사용됩니다.
1、MethodBeforeAdvice 예제
실제 비즈니스 로직을 포함한 클래스를 생성합니다.
파일: A.java
package com.w3codebox; public class A { public void m(){System.out.println("actual business logic");} }
이제 MethodBeforeAdvice 인터페이스를 구현한 컨설턴트 클래스를 생성해 보겠습니다.
파일: BeforeAdvisor.java
package com.w3codebox; import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAdvice; public class BeforeAdvisor implements MethodBeforeAdvice{ @Override public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println("실제 로직 이전 추가적인 관심사"); } }
xml 파일에서 생성하십시오.3bean이 하나씩 생성됩니다. 하나는 A 클래스를 위한 것이고, 두 번째는 Advisor 클래스를 위한 것이며, 세 번째는 ProxyFactoryBean 클래스.
파일: applicationContext.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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="obj" class="com.w3codebox.A"></bean> <bean id="ba" class="com.w3codebox.BeforeAdvisor"></bean> <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="obj"></property> <property name="interceptorNames"> <list> <value>ba</value> </list> </property> </bean> </beans>
ProxyFactoryBean 클래스를 이해해 보겠습니다:
ProxyFactoryBean Spring Famework이 제공하는 클래스로, 다음을 포함하고 있습니다.2property target과 interceptorNames. A 클래스의 인스턴스는 대상 객체로, 컨설턴트 클래스의 인스턴스는 인터셉터로 간주됩니다. 위의 xml 파일과 같이 컨설턴트 객체를 리스트 객체로 전달해야 합니다.
ProxyFactoryBean 클래스의 작성은 다음과 같습니다:
public class ProxyFactoryBean{ private Object target; private List interceptorNames; //getters and setters }
이제 실제 메서드를 호출해 보겠습니다.
file: Test.java
package com.w3codebox; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(r); A a=factory.getBean("proxy",A.class); a.m(); } }
output
실제 로직 이전 추가적인 관심사 실제 비즈니스 로직
MethodBeforeAdvice에서 다른 정보를 출력하면, 예를 들어 메서드 이름, 메서드 파라미터, 대상 객체, 대상 객체 클래스 이름, 프록시 클래스 등을 출력할 수 있습니다.
귀하께서는 두 개의 클래스인 BeforeAdvisor.java와 Test.java를 변경하시면 됩니다.
파일: BeforeAdvisor.java
package com.w3codebox; import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAdvice; public class BeforeAdvisor implements MethodBeforeAdvice{ @Override public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println("실제 로직 이전 추가적인 관심사"); System.out.println("메서드 정보:");+method.getName()+" "+method.getModifiers()); System.out.println("인자 정보:"); for(Object arg:args) System.out.println(arg); System.out.println("대상 Object:");+target); System.out.println("대상 객체 클래스 이름: ");+target.getClass().getName()); } }
file: Test.java
package com.w3codebox; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(r); A a=factory.getBean("proxy",A.class); System.out.println("프록시 클래스 이름: ");+a.getClass().getName()); a.m(); } }
output
프록시 클래스 이름: com.w3codebox.A$EnhancerByCGLIB$409872b1 실제 로직 이전 추가적인 관심사 메서드 정보:m 1 인자 정보: 대상 Object:com.w3codebox.A@11dba45 대상 객체 클래스 이름: com.w3codebox.A 실제 비즈니스 로직
AfterReturningAdvice 예제
실제 비즈니스 로직을 포함한 클래스를 생성합니다.
파일: A.java
이전 예제와 같습니다.
지금, AfterReturningAdvice 인터페이스를 구현한 상담자 클래스를 생성합니다.
파일: AfterAdvisor.java
package com.w3codebox; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; public class AfterAdvisor implements AfterReturningAdvice{ @Override public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { System.out.println("추가적인 관심사는 조언을 반환한 후에 추가됩니다"); } }
이전 예제와 같이 xml 파일을 생성하려면 여기서 고문 프로그램 클래스를 변경하십시오.
파일: applicationContext.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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="obj" class="com.w3codebox.A"></bean> <bean id="ba" class="com.w3codebox.AfterAdvisor"></bean> <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="obj"></property> <property name="interceptorNames"> <list> <value>ba</value> </list> </property> </bean> </beans>
file: Test.java
이전 예제와 같습니다.
output
실제 비즈니스 로직 추가적인 관심사는 조언을 반환한 후에 추가됩니다
3)MethodInterceptor(AroundAdvice) 예제
실제 비즈니스 로직을 포함한 클래스를 생성합니다.
파일: A。java
이전 예제와 같습니다.
이제, MethodInterceptor 인터페이스를 구현한 고문 클래스를 생성하십시오.
파일: AroundAdvisor.java
package com.w3codebox; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; public class AroundAdvisor implements MethodInterceptor{ @Override public Object invoke(MethodInvocation mi) throws Throwable { Object obj; System.out.println("실제 로직 이전 추가적인 관심사"); obj=mi.proceed(); System.out.println("실제 로직 이후 추가적인 관심사"); return obj; } }
이전 예제와 같이 xml 파일을 생성하려면 여기서 고문 프로그램 클래스를 변경하십시오.
파일: applicationContext.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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="obj" class="com.w3codebox.A"></bean> <bean id="ba" class="com.w3codebox.AroundAdvisor"></bean> <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="obj"></property> <property name="interceptorNames"> <list> <value>ba</value> </list> </property> </bean> </beans>
file: Test.java
이전 예제와 같습니다.
output
실제 로직 이전 추가적인 관심사 실제 비즈니스 로직 실제 로직 이후 추가적인 관심사
4ThrowsAdvice 예제
실제 비즈니스 로직을 포함한 클래스를 생성합니다.
파일: Validator.java
package com.w3codebox; public class Validator { public void validate(int age)throws Exception{ if(age<18){ throw new ArithmeticException("Not Valid Age"); } else{ System.out.println("vote confirmed"); } } }
이제, ThrowsAdvice 인터페이스를 구현하는 조언자 클래스를 생성합니다.
파일: ThrowsAdvisor.java
package com.w3codebox; import org.springframework.aop.ThrowsAdvice; public class ThrowsAdvisor implements ThrowsAdvice{ public void afterThrowing(Exception ex){ System.out.println("additional concern if exception occurs"); } }
이전 예제와 같이 xml 파일을 생성하려면, Validator 클래스와 Advisor 클래스를 변경해야 합니다.
파일: applicationContext.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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="obj" class="com.w3codebox.Validator"></bean> <bean id="ba" class="com.w3codebox.ThrowsAdvisor"></bean> <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="obj"></property> <property name="interceptorNames"> <list> <value>ba</value> </list> </property> </bean> </beans>
file: Test.java
package com.w3codebox; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(r); Validator v=factory.getBean("proxy",Validator.class); try{ v.validate(12); }catch(Exception e){e.printStackTrace();} } }
output
java.lang.ArithmeticException: Not Valid Age additional concern if exception occurs at com.w3codebox.Validator.validate(Validator.java:7) at com.w3codebox.Validator$FastClassByCGLIB$562915cf.invoke(<generated>) at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191) at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invoke Joinpoint(Cglib2AopProxy.java:692) at org.springframework.aop.framework.ReflectiveMethodInvocation. proceed(ReflectiveMethodInvocation.java:150) at org.springframework.aop.framework.adapter.ThrowsAdviceInterceptor. invoke(ThrowsAdviceInterceptor.java:124) at org.springframework.aop.framework.ReflectiveMethodInvocation. proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor. intercept(Cglib2AopProxy.java:625) at com.w3codebox.Validator$EnhancerByCGLIB$4230ed28.validate(<generated>) at com.w3codebox.Test.main(Test.java:15)