Annotation方式实现AOP

使用Annotation方式重新实现昨天的例子。重新修改SecurityHandler类,使用@Aspect声明此类为一个使用了AOP技术的切面。提供一个方法allMethod(),该方法无参且无返回类型也没有具体的代码实现,用于定义Pointcut(切入点)。Pointcut的内容是一个表达式,用于描述对哪些方法进行切入(类似于拦截的作用)。

定义Advice,字面上是“建议”的意思,这里可以理解为所要向切入点中插入的其他操作。@Before表示该Advice是在切入点中方法执行之前被执行,其参数是指在哪个Pointcut中织入该Advice。除了Before当然还有其它的了,可以百度一下。

该SecurityHandler类的完整代码如下:

package cn.ineeke.spring;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class SecurityHandler {
@Pointcut("execution(* *(..))")
private void allMethod(){
}
@Before("allMethod()")
private void printSomthing(){
System.out.println("--------Security----------");
}
}

在execution(* *(..))中,其格式为execution(返回类型 方法名(参数)),“*”和“..”均表示所有。

接下来需要启用Aspectj对Annotation的支持,并将Aspect类和目标对象配置到IOC容器中。修改applicationContext.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-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<aop:aspectj-autoproxy/>
<bean id="securityHandler" class="cn.ineeke.spring.SecurityHandler"/>
<bean id="userDAO" class="cn.ineeke.spring.UserDAOImpl"/>
</beans>

最后再写个测试类测试一下。

package cn.ineeke.spring;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String[] args) {
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
IUserDAO userDAO = (IUserDAO) factory.getBean("userDAO");
userDAO.getUser();
}
}

最后需要注意的是,这里用于定义Pointcut的allMethod()方法并不会被执行,它仅仅只是起到一个标识的作用。不信的话可以在allMethod()方法中写点什么,运行一下看看是否会被执行。


除非另有声明,本站遵循【署名-非商业性使用-相同方式共享 3.0 共享协议】授权。

转载原创文章请注明,转载自:Neeke[http://www.ineeke.com]

本文链接: http://www.ineeke.com/archives/spring-aop-annotation/

2009年1月28日 | 归档于 J2EE技术 | 没有评论
本文目前尚无任何评论.

发表评论

XHTML: 您可以使用这些标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">
n:-zy n:-zr n:-zan n:-xf n:-wx n:-tz n:-tt n:-ts n:-sy n:-st n:-ss n:-sk n:-qd n:-pz n:-lh n:-kun n:-ku n:-hx n:-hd n:-gt n:-gg n:-bz

NOTICE: You should type some Chinese word (like “你好”) in your comment to pass the spam-check, thanks for your patience!