使用注解很容易实现AOP,也省去了xml上下文配置中的繁琐配置项,我们先建立几个类:包括interface类Animal、其实现类Tiger, 再写一个切面类FeedReady,即我们需要喂养接口类动物的一个实现类老虎。然后我们要做的是通过注解实现AOP编程在喂养方法执行之前我们需要准备食物,喂养完成后需要清理喂养的地方。类定义如下:本文地址:http://www.04007.cn/article/879.html,未经许可,不得转载.
//interface类Animal package wireaop; public interface Animal { public void feed(); } //interface的实现类Tiger package wireaop; public class Tiger implements Animal { @Override public void feed() { // TODO Auto-generated method stub System.out.println("喂养动物"); } } //再写一个切面类 package wireaop; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; //定义一个切面 @Aspect public class FeedReady { //在连接点定义一个切入点 @Before("execution(* Tiger.*(..))") public void food() { System.out.println("准备食物"); } @After("execution(* Tiger.*(..))") public void clear() { System.out.println("清理屋子"); } }
本文地址:http://www.04007.cn/article/879.html,未经许可,不得转载.
上面的切面FeedReady定义中我们没有继承Spring框架的任何类,只是通过注解实现将当前类定义为一个切面交给spring管理,并定义了两个方法分别注解为Before方法执行和After方法执行中。然后我们完善Spring的上下文配置bean.xml以及我们的测试类,各配置及输出结果如下:本文地址:http://www.04007.cn/article/879.html,未经许可,不得转载.
//Spring的上下文配置bean.xml <?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.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <aop:aspectj-autoproxy /> <bean id="tiger" class="wireaop.Tiger" /> <bean id="feedready" class="wireaop.FeedReady" /> </beans> //测试类代码 package com.kermit.dotest; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import wireaop.Animal; public class Testwire { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); Animal tiger = (Animal) context.getBean("tiger"); tiger.feed(); } }本文地址:http://www.04007.cn/article/879.html,未经许可,不得转载.
/运行结果如下:
准备食物
喂养动物
清理屋子本文地址:http://www.04007.cn/article/879.html,未经许可,不得转载.
在执行的过程中遇到报错:org.springframework.context.support.AbstractApplicationContext refresh 警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tiger' defined in class path resource [bean.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: Pointcut is not well-formed: expecting ')' at character position 0 execution(* Tiger.*(..) 排查发现双引号里的execution()缺少一个括号,但在IDE编写代码的时候并不报错,双引号里的代码编写看来要小心啊。本文地址:http://www.04007.cn/article/879.html,未经许可,不得转载.
本文地址:http://www.04007.cn/article/879.html 未经许可,不得转载. 手机访问本页请扫描右下方二维码.
![]() |
![]() |
手机扫码直接打开本页面 |