AOP中的引语自动装配通知
AOP中的注解自动装配通知
AOP中的注解自动装配通知
一、创建一个注解类:
注意:aop的引入
package cn.****.util; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class ServiceImpl implements Service { /** * @Before("execution(* work())")方法中的第一个参数“*”是返回值,第二个参数“work()”是方法的名 * */ @Before("execution(* goWork())") public void eat(JoinPoint jp) { // TODO Auto-generated method stub System.out.println("I'm eating!!!"); /* * 输出的结果是: I'm eating!!! 我正在工作! */ } /** * After(execution(* * cn.****.service.Emp*.*(..)))方法的第一个参数(*)是返回值,第二个参数是位于cn.****.service * 包下的前缀是Emp的类的所有方法,((..))代表的是方法的参数可以是可变的参数 * */ @After("execution(* cn.****.service.Emp*.*(..))") public void goCompany() { // TODO Auto-generated method stub System.out.println("I want to go home"); } /** * 总结返回值有void和*两种,方法的名字的表示方式有直接写方法的名字、写出那个类的哪个方法或类和方法的名字模糊匹配*/ @AfterThrowing(pointcut = "execution(* *..EmpService*.*(..))", throwing = "ex") public void leave(Exception ex) { // TODO Auto-generated method stub System.out.println("I want leav"); } @Before("execution(* cn.****.service.EmpServiceImpl.*(..))") public void goHome() { // TODO Auto-generated method stub System.out.println("I want go Home"); } @Around("execution(* *..Emp*.goWork(..))") public void signIn() { // TODO Auto-generated method stub System.out.println("I around before"); System.out.println("I around after"); } }
xml中的部分代码如下:
<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="empServiceImpl" class="cn.****.service.EmpServiceImpl"/> <bean id="serviceImpl" class="cn.****.util.ServiceImpl"></bean> <aop:aspectj-autoproxy/> </beans>源代码如下: