Spring AOP的配置

Beans.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:context="http://www.springframework.org/schema/context"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
>
<!-- 配置被代理对象 -->
<bean id="testService" class="com.dqd.aop.TestService">
	<property name="name" value="dqd"></property>
</bean> 	


 <!-- 配置前置通知 -->
<bean id="myMethodBeforeAdvice" class="com.dqd.aop.MyMethodBeforeAdvice" />
 
 
 <!-- 配置代理对象 -->
 <bean id="proxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean">
 	<!-- 代理接口集 -->
 	<property name="proxyInterfaces">
 		<list>
 			<value>com.dqd.aop.TestInter</value>
 			<value>com.dqd.aop.TestInter2</value>
 		</list>
 	</property>
 	<!-- 把通知织入代理对象 -->
 	<property name="interceptorNames">
 		<!-- 相当于把前置通知和代理对象关联起来,也可理解为拦截器 -->
 		<value>myMethodBeforeAdvice</value>
 	</property>
 	<!-- 配置被代理对象,可以指定 -->
 	<property name="target" ref="testService" /><!-- 指向代理对象 -->

 </bean>
 </beans>


一个实现两个接口的类:


package com.dqd.aop;

public class TestService implements TestInter,TestInter2{
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	
	public void sayHello(){
		System.out.println("hi !"+name);
	}
	public void sayBey(){
		System.out.println("Bye !"+name);
	}
}


通知的配置:


package com.dqd.aop;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;


public class MyMethodBeforeAdvice implements MethodBeforeAdvice {

	@Override
	public void before(Method method, Object[] args, Object target)
			throws Throwable {
		// TODO Auto-generated method stub
		
		System.out.println("记录日志:"+method.getName());
	}
	
}


Test:


package com.dqd.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class app1 {
	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("com/dqd/aop/Beans.xml");
		TestInter ts = (TestInter) ac.getBean("proxyFactoryBean");
		//注意ac中含有接口1和2但是我们使用的接口1来接受的,但是可以强转为接口2的类型
		ts.sayHello();
		((TestInter2)ts).sayBey();
	}
}















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值