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()方法中写点什么,运行一下看看是否会被执行。


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

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

除非另有声明,本网站采用知识共享“署名 2.5 中国大陆”许可协议授权。

您可以自由: 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 创作演绎作品

惟须遵守下列条件: 署名 — 您必须按照作者或者许可人指定的方式对作品进行署名。

你可能感兴趣的:(AOP,annotation,职场,休闲)