Spring AOP

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、测试结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值