业务类与以前相同,做用不改变
Log类java
public class Log { public void before(){ System.out.println("——————方法执行前"); } public void after(){ System.out.println("——————方法执行后"); } }
Service类spring
public interface Service { public void add(); public void update(); public void delete(); public void search(); }
ServiceImpl类ide
public class ServiceImpl implements Service{ @Override public void add() { System.out.println("增长用户"); } @Override public void update() { System.out.println("修改用户"); } @Override public void delete() { System.out.println("删除用户"); } @Override public void search() { System.out.println("查询用户"); } }
配置文件修改一下,增长aop:aspectj-autoproxy/。它会自动去找aop。测试
<?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: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="service" class="ServiceImpl"/> <bean id="log" class="Log"/> <aop:aspectj-autoproxy/> </beans>
Log类前面加上注解,@Aspect,表示Log类是一个切面,方法前面加上@before或者其余,表示为前置通知或者其余通知。括号填写表达式execution(* Service.*(..)表示切入点,第一个*表示全部返回值,Service表示全限定名,第二个*表示全部方法。(..)表示全部参数。.net
import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class Log { @Before("execution(* ServiceImpl.*(..))") public void before(){ System.out.println("——————方法执行前"); } @After("execution(* ServiceImpl.*(..))") public void after(){ System.out.println("——————方法执行后"); } }
执行结果
code
环绕通知
环绕通知特殊一点,须要参数ProceedingJoinPoint。而后调用ProceedingJoinPoint的proceed()来执行目标方法。视频
public class Log { @Before("execution(* ServiceImpl.*(..))") public void before(){ System.out.println("——————方法执行前"); } @After("execution(* ServiceImpl.*(..))") public void after(){ System.out.println("——————方法执行后"); } @Around("execution(* ServiceImpl.*(..))") public void aroud(ProceedingJoinPoint jp)throws Throwable{ System.out.println("环绕前"); jp.proceed(); System.out.println("环绕后"); } }
测试一下
目标方法也执行了。视频中到这一步,虽然方法也执行了,可是后面也有报错信息,显示没有返回object。由于proceed()会返回一个Object,可是咱们没有处理。这里能够把around方法改为返回一个Object。而后返回proceed()执行后的结果就能够了。可是并无处理返回的Object。也没有报错信息。多是spring版本不一样,有点改变吧。xml