Spring AOP支持5种类型的增强【通知】,分别是:前置增强,后置增强,环绕增强,异常抛出增强,引介增强
以下是前置增强的一个示例:
1、PeopleDao
package com.twj.advisor;
public interface PeopleDao {
public void eating(String name);
}
2、PeopleDaoImpl
package com.twj.advisor;
public class PeopleDaoImpl implements PeopleDao{
public void eating(String name){
System.out.println(name+"is Eating");
}
}
3、BeforeAdvice
package com.twj.advisor;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class Peopleabeforedvisor implements MethodBeforeAdvice {
@Override
public void before(Method arg0, Object[] arg1, Object arg2)
throws Throwable {
// TODO Auto-generated method stub
String methodname=arg0.getName();
String peoplename=(String) arg1[0];
System.out.println(methodname+" run");
System.out.println(peoplename+"在洗手准备去吃饭啦");
}
}
4、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="peopleabeforedvisor" class="com.twj.advisor.Peopleabeforedvisor"></bean>
<bean id="target" class="com.twj.advisor.PeopleDaoImpl"></bean>
<bean id="people" class="org.springframework.aop.framework.ProxyFactoryBean"
p:proxyInterfaces="com.twj.advisor.PeopleDao" p:interceptorNames="peopleabeforedvisor"
p:target-ref="target" />
</beans>
5、测试
package com.twj.advisor;
import org.springframework.aop.BeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestBeforeAdvisor {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String config="/applicationContext.xml";
ApplicationContext ctx=new ClassPathXmlApplicationContext(config);
PeopleDao p=(PeopleDao) ctx.getBean("people");
p.eating("Xiaoming");
}
}
6、测试结果: