主函数:
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
Waiter w=(Waiter)ctx.getBean("waiter");
w.greetto("yinfan");
XML:
<aop:aspectj-autoproxy/>
<bean id="waiter" class="aspect.implewaiter"></bean>
<bean class="aspect.pregreetingaspect"/>
目标类:
package aspect;
public class implewaiter implements Waiter {
public void greetto(String name) {
// TODO Auto-generated method stub
System.out.println("greet to "+name);
}
public void serveto(String name) {
// TODO Auto-generated method stub
System.out.println("server to "+name);
}
}
切面代码:
package aspect;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class pregreetingaspect {
@Before("execution(* greetto(..))")
public void before()
{
System.out.println("how are you ");
}
}
结果:
how are you
how are you
greet to yinfan
你看,有两个how are you 呢?
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
Waiter w=(Waiter)ctx.getBean("waiter");
w.greetto("yinfan");
XML:
<aop:aspectj-autoproxy/>
<bean id="waiter" class="aspect.implewaiter"></bean>
<bean class="aspect.pregreetingaspect"/>
目标类:
package aspect;
public class implewaiter implements Waiter {
public void greetto(String name) {
// TODO Auto-generated method stub
System.out.println("greet to "+name);
}
public void serveto(String name) {
// TODO Auto-generated method stub
System.out.println("server to "+name);
}
}
切面代码:
package aspect;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class pregreetingaspect {
@Before("execution(* greetto(..))")
public void before()
{
System.out.println("how are you ");
}
}
结果:
how are you
how are you
greet to yinfan
你看,有两个how are you 呢?
本文通过一个具体的示例展示了如何使用Spring AOP结合AspectJ实现方法调用前的增强处理。具体步骤包括配置Spring上下文,定义目标类和服务类,以及编写AspectJ切面代码。运行结果验证了切面功能的有效性。

被折叠的 条评论
为什么被折叠?



