业务接口
package dao; public interface UserDao { public void addUser(); }
接口实现
package dao; public class UserDaoImpl implements UserDao { @Override public void addUser() { // TODO Auto-generated method stub System.out.println("添加用户"); } }
代理类
package aspect; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; @Aspect public class UserDaoAspect { //类中开发切入点和各种通知 @Pointcut("execution(* dao..*.*(..))") //切入点 签名就是下面的方法名 public void sayHello(){}; @Before("sayHello()") //前置通知 public void startSay(){ System.out.println("Good Morning"); } @AfterReturning("sayHello()") //后置通知 public void endSay(){ System.out.println("bye bye"); } @AfterThrowing("sayHello()") //异常通知 public void doThrows(){ System.out.println("异常通知"); } @After("sayHello()") //后通知 public void doFinally(){ System.out.println("最终执行"); } }
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" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <bean id="userDao" class="dao.UserDaoImpl" /> <bean id="aspectj" class="aspect.UserDaoAspect"></bean> <aop:aspectj-autoproxy/> </beans>
测试类
package test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import dao.UserDao; import dao.UserDaoImpl; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); UserDao dao=(UserDao)context.getBean("userDao"); dao.addUser(); } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/14412.html