package com.Spring5.AOP; import org.springframework.stereotype.Component; @Component(value = "user111") public class User { public void add(){ System.out.println("add ... .. ..."); } }
package com.Spring5.AOP; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @Component @Aspect public class UserProxy { @Before(value = "execution(* com.Spring5.AOP.User.add())") public void bf(){ System.out.println("前置通知 ... .. .. "); } @AfterReturning(value = "execution(* com.Spring5.AOP.User.add())") public void af(){ System.out.println("后置通知 ... .. .. "); } @Around(value = "execution(* com.Spring5.AOP.User.add())") public void hr(ProceedingJoinPoint p) throws Throwable{ System.out.println("环绕通知前 ... .. .. "); p.proceed(); System.out.println("环绕通知后 ... .. .. "); } @AfterThrowing(value = "execution(* com.Spring5.AOP.User.add())") public void aft(){ System.out.println("异常通知 ... .. .. "); } @After(value = "execution(* com.Spring5.AOP.User.add())") public void fina(){ System.out.println("最终通知 ... .. .. "); } }
<context:component-scan base-package="com.Spring5.AOP"></context:component-scan>
利用@Component
@Aspect
用来表示这是一个增强类
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
@Before
@AfterReturning
@Around
@AfterThrowing
@After
@Before(value = "execution(* com.Spring5.AOP.User.add())")
,具体写法在上一篇文章有提到<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="com.Spring5.AOP"></context:component-scan> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>
package com.Spring5.TestSpring; import com.Spring5.AOP.User; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestAOP { @Test public void testaop(){ ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml"); User user=context.getBean("user111",User.class); user.add(); } }