package com.kruders.spring.aop;
public class BusinessImpl implements BusinessService {
public void doSomeThing() {
System.out.println("Do Something Here");
int x = 5/0;
}
}
<?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">
<bean id="businessService" class="com.kruders.spring.aop.BusinessImpl" />
<!-- Advice -->
<bean id="businessAdvice" class="com.kruders.spring.advice.BusinessAdvice" />
<bean id="businessServiceProxy"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="businessService" />
<property name="interceptorNames">
<list>
<value>businessAdvice</value>
</list>
</property>
</bean>
</beans>
package com.kruders.spring.advice;
import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;
public class BusinessAdvice implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice, MethodInterceptor {
@Override
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println("Before method is called (by " + this.getClass().getName() + ")");
}
@Override
public void afterReturning(Object returnValue, Method method,
Object[] args, Object target) {
System.out.println("After method is called (by " + this.getClass().getName() + ")");
}
public void afterThrowing(ArithmeticException e) throws Throwable {
System.out.println("After throwing method is called");
}
@Override
public Object invoke(MethodInvocation method) throws Throwable {
System.out.println("Around method is called");
System.out.println("Around before is running");
method.proceed();
System.out.println("Around after is running");
return null;
}
}
package com.kruders.spring.core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.kruders.spring.aop.BusinessService;
public class Main {
public static void main(String args[]) {
ApplicationContext appContext = new ClassPathXmlApplicationContext("Spring-Business.xml");
BusinessService businessService = (BusinessService)appContext.getBean("businessServiceProxy");
//这句话相当于spring框架通过配置文件的第10行new一个BusinessServcie类的实例出来
try {
businessService.doSomeThing();
} catch(ArithmeticException ae) {
}
}
}
原文:http://kruders.com/spring/spring-aop-advice/
源代码:http://pan.baidu.com/share/link?shareid=425056&uk=3878681452