一个简单的Spring的AOP例子

本文介绍了一个使用Spring AOP实现的通知机制示例,包括前置通知、后置通知及环绕通知,并通过具体代码展示了如何对目标方法进行增强。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


package aop;
/**
* 目标对象的接口
*/
public interface Student {
public void addStudent(String name);
}



package aop;
/**
* 目标对象
*/
public class StudentImpl implements Student {

public void addStudent(String name) {
System.out.println(" 欢迎 " + name + " 你加入Spring家庭! ");
}
}



package aop;

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

/**
* 前置通知
*/
public class BeforeAdvice implements MethodBeforeAdvice {

public void before(Method method, Object[] args, Object target)
throws Throwable {

System.out.println(" 这是BeforeAdvice类的before方法. ");

}
}


package aop;

import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;

/**
* 后置通知
*/
public class AfterAdvice implements AfterReturningAdvice {

public void afterReturning(Object returnValue, Method method,
Object[] args, Object target) throws Throwable {
System.out.println("这是AfterAdvice类的afterReturning方法.");
}

}


package aop;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* 环绕通知
*/
public class CompareInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
Object result = null;
String stu_name = invocation.getArguments()[0].toString();
if (stu_name.equals("dragon")) {
// 如果学生是dragon时,执行目标方法,
result = invocation.proceed();
} else {
System.out.println("此学生是" + stu_name + "而不是dragon,不批准其加入.");
}
return result;
}
}




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="beforeAdvice" class="aop.BeforeAdvice"></bean>
<bean id="afterAdvice" class="aop.AfterAdvice"></bean>
<bean id="compareInterceptor" class="aop.CompareInterceptor"></bean>
<bean id="studenttarget" class="aop.StudentImpl"></bean>
<bean id="student"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>aop.Student</value>
</property>
<property name="interceptorNames">
<list>
<value>beforeAdvice</value>
<value>afterAdvice</value>
<value>compareInterceptor</value>
</list>
</property>
<property name="target">
<ref bean="studenttarget" />
</property>
</bean>

</beans>




package aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
/**
* 测试代码
*/
public class Test {

public static void main(String[] args) {
ApplicationContext ctx = new FileSystemXmlApplicationContext("/src/applicationContext.xml");
Student s = (Student)ctx.getBean("student");
s.addStudent("aaa");
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值