經過springAPI來實現須要經過實現接口或者繼承來構建關注點。自定義實現的話就不須要了。Log代碼以下java
public class Log { public void before(){ System.out.println("——————方法執行前"); } public void after(){ System.out.println("——————方法執行後"); } }
Service和ServiceImpl代碼不變。spring
public interface Service { public void add(); public void update(); public void delete(); public void search(); }
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("查詢用戶"); } }
beans配置修改以下。在aop:config裏增長aop:aspect,ref是關聯的關注點。aop:pointcut一樣是切入點。befor和after對應前置通知和後置通知。express
<?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:config> <aop:aspect ref="log"> <aop:pointcut id="pointcut" expression="execution(* ServiceImpl.*(. .))"/> <aop:before method="before" pointcut-ref="pointcut"/> <aop:after method="after" pointcut-ref="pointcut"/> </aop:aspect> </aop:config> </beans>
測試以下
ide