English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

esempio di Spring AOP

fornisce Spring1.2 vecchia AOP un esempio di implementazione basato su dtd.

Nonostante sia supportato in Spring 3, l'uso dell'Advice con Spring aop e AspectJ che impareremo nella pagina successiva.

La vecchia implementazione aop di spring1.2 supporta 4 tipi di Advice.

Before Adviceche viene eseguita prima della chiamata del metodo reale. After Adviceche viene eseguita dopo la chiamata del metodo reale. Se il metodo restituisce un valore, viene eseguita dopo il valore di ritorno. Around Adviceche viene eseguita prima e dopo la chiamata del metodo reale. Throws Advicese il metodo reale solleva un'eccezione, eseguire questa Advice.

Attenzione: Per comprendere i concetti fondamentali di Spring AOP, visitare la pagina precedente.

Gerarchia delle Advice

Facciamo un'occhiata alla seguente tabella per comprendere la gerarchia delle Advice:

tutti sono interfacce dell'aop.

MethodBeforeAdvice l'interfaccia estesa da BeforeAdvice interfaccia.

AfterReturningAdvice l'interfaccia estesa da AfterAdvice interfaccia.

ThrowsAdvice Interfaccia che estende AfterAdvice interfaccia.

MethodInterceptor Interfaccia che estende Intercettore Interfaccia. Utilizzata intorno all'Advice.

1. Esempio di MethodBeforeAdvice

crea una classe che contiene la logica aziendale reale.

File: A.java

package com.w3codebox;
public class A {
public void m(){System.out.println("logica aziendale reale");}
}

Ora, create una classe consigliere che implementi l'interfaccia MethodBeforeAdvice.

File: 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("preoccupazione aggiuntiva prima della logica reale");
	}
}

Nel file xml, create 3 bean, uno per la classe A, il secondo per la classe Advisor e il terzo per ProxyFactoryBean Classe.

文件: 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>

Comprendere la classe ProxyFactoryBean:

ProxyFactoryBean La classe è fornita dal framework Spring. Contiene 2 proprietà, target e interceptorNames. L'istanza della classe A sarà considerata l'oggetto target, mentre l'istanza della classe del consigliere sarà considerata l'intercettore. Dovete passare l'oggetto consigliere come oggetto lista, come indicato nel file xml fornito.

La scrittura della classe ProxyFactoryBean è la seguente:

public class ProxyFactoryBean{
private Object target;
private List interceptorNames;
//getter e setter
}

Ora, chiamiamo il metodo reale.

文件: 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();
}
}

输出

preoccupazione aggiuntiva prima della logica reale
logica aziendale reale

Nella MethodBeforeAdvice possiamo stampare altre informazioni, come il nome del metodo, i parametri del metodo, l'oggetto target, il nome della classe dell'oggetto target, la classe proxy, ecc.

Dovete modificare solo due classi, BeforeAdvisor.java e Test.java.

File: 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("preoccupazione aggiuntiva prima della logica reale");
		System.out.println("info del metodo:" + method.getName() + " " + method.getModifiers());
		System.out.println("Informazioni sugli argomenti:");
		for(Object arg: args)
			System.out.println(arg);
		System.out.println("Oggetto target:" + target);
		System.out.println("Nome della classe dell'oggetto target: " + target.getClass().getName());
	}
}

文件: 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("Nome della classe proxy: " + a.getClass().getName());
	a.m();
}
}

输出

Nome della classe proxy: com.w3codebox.A$EnhancerByCGLIB$409872b1
preoccupazione aggiuntiva prima della logica reale
Informazioni sul metodo: m 1
Informazioni sugli argomenti:
Oggetto target: com.w3codebox.A@11dba45
Nome della classe dell'oggetto target: com.w3codebox.A
logica aziendale reale

Esempio di AfterReturningAdvice

crea una classe che contiene la logica aziendale reale.

File: A.java

come nell'esempio precedente

Ora, crea una classe consulente che implementa l'interfaccia AfterReturningAdvice.

File: 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("concern aggiuntivo dopo il ritorno dell'advice");
	}
}

crea un file xml come nell'esempio precedente, devi solo cambiare la classe del consulente qui.

文件: 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 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>

文件: Test.java

come nell'esempio precedente

输出

logica aziendale reale
preoccupazione aggiuntiva dopo il ritorno dell'advice

3) Esempio di MethodInterceptor (AroundAdvice)

crea una classe che contiene la logica aziendale reale.

File: A.java

come nell'esempio precedente

Ora, crea una classe consulente che implementa l'interfaccia MethodInterceptor.

File: 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("preoccupazione aggiuntiva prima della logica reale");
		obj = mi.proceed();
		System.out.println("preoccupazione aggiuntiva dopo la logica reale");
		return obj;
	}
}

crea un file xml come nell'esempio precedente, devi solo cambiare la classe del consulente qui.

文件: 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>

文件: Test.java

come nell'esempio precedente

输出

preoccupazione aggiuntiva prima della logica reale
logica aziendale reale
preoccupazione aggiuntiva dopo la logica reale

Esempio di ThrowsAdvice

crea una classe che contiene la logica aziendale reale.

File: Validator.java

package com.w3codebox;
public class Validator {
	public void validate(int age) throws Exception{
		se (age<18){
			lancia una nuova ArithmeticException("Età non valida");
		}
		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>

文件: 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();}
}
}

输出

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(<generato>)
	at com.w3codebox.Test.main(Test.java:15)