- 在面向切面编程时,使用< aop:aspect>,在进行事务管理时,使用< aop:advisor>
- < aop:advisor>定义通知器跟切面一样,也包括通知和切点,但定义< aop:advisor>中引用的通知时,通知必须实现Advice接口
语法
<aop:advisor advice-ref="事务类bean的id" pointcut-ref="切入点id"/>
示例
- 首先,我们定义一个接口SleepAdvisor和这个接口的实现SleepImplAdvisor
- SleepAdvisor.java
public interface SleepAdvisor{ public void sleep(String name); }
|
- SleepImplAdvisor.java
public class SleepImplAdvisor implements SleepAdvisor{ private String name; @Override public String sleep(String name) { System.out.println("I'm sleeping!"); return "sleep"; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
- 创建一个通知类
- AopAdvisorHelper.java
public class AopAdvisorHelper implements MethodBeforeAdvice, AfterReturningAdvice{ @Override public void before(Method method, Object[] args, Object target) throws Throwable{ System.out.println("类" + target + "执行了" + method.getName() + "方法。"); //数据库做一个插入操作 }
/** * returnValue 方法返回值 * method 执行的方法 * args 执行方法的参数 * target 执行的类 */ @Override public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable{ System.out.println("类" + target + "执行了" + method.getName() + "方法。"); } }
|
- 配置通知器
- application.xml
<bean id="aopAdvisorHelper" class="com.exi.aop.advisor.AopAdvisorHelper"></bean> <!-- aop配置 --> <aop:config> <aop:pointcut id="sleepPointcut" expression="execution(* com.exi.aop.advisor.*.*(..))" /> <aop:advisor pointcut-ref="sleepPointcut" advice-ref="aopAdvisorHelper" /> </aop:config> |
- 测试类
@Test public class BeanTest{ //aop-advisor实现aop拦截 ApplicationContext context = new ClassPathXmlApplicationContext("spring-aop.xml"); ISleepAdvisorable sleeper = (ISleepAdvisorable) context.getBean("human"); sleeper.sleep("human"); System.out.println("======================================="); ICarAdvisorable car = (ICarAdvisorable) context.getBean("carableAdvisorImpl"); car.byCar(); } } |
来自 <https://www.cnblogs.com/hejj-bk/p/11413614.html>