上篇文章我们对AOP的相关概念进行了解,接下来我们将采用Annotation的方式完成AOP的实现.当然也可以用XML的配置方式进行实现.
采用Annotation完成AOP示例
1、spring的依赖包配置
SPRING_HOME/dist/spring.jar
SPRING_HOME/lib/log4j/log4j-1.2.14.jar
SPRING_HOME/lib/jakarta-commons/commons-logging.jar
SPRING_HOME/lib/aspectj/*.jar
2、将横切性关注点模块化,建立SecurityHandler.java
package com.bjpowernode.spring;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
//采用注解指定SecurityHandler为Aspect
@Aspect
public class SecurityHandler {
/**
* 定义Pointcut,Pointcut的名称为addAddMethod(),此方法没有返回值和参数
* 该方法就是一个标识,不进行调用
*/
@Pointcut("execution(* add*(..))")
private void addAddMethod(){};
/**
* 定义Advice,表示我们的Advice应用到哪些Pointcut订阅的Joinpoint上
*/
@Before("addAddMethod()")
//@After("addAddMethod()")
private void checkSecurity() {
System.out.println("-------checkSecurity-------");
}
}
3、采用注解指定SecurityHandler为Aspect
4、采用注解定义Advice和Pointcut
5、启用AspectJ对Annotation的支持,并且将目标类和Aspect类配置到IoC容器中
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<!-- 启用AspectJ对Annotation的支持 -->
<aop:aspectj-autoproxy/>
<bean id="userManager" class="com.bjpowernode.spring.UserManagerImpl"/>
<bean id="securityHandler" class="com.bjpowernode.spring.SecurityHandler"/>
</beans>
6、开发客户端
package com.bjpowernode.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");
UserManager userManager = (UserManager)factory.getBean("userManager");
userManager.addUser("张三", "123");
}
}
小结:
上述实例的主要功能是在进行增加用户的时候进行安全检查,本实例通过System.out.println("-------checkSecurity-------");来代替具体的检查内容.如果不用AOP思想来实现的话,那些与商业逻辑无关的重复代码遍布在整个程序中。实际的工程项目中涉及到的类和函数,远远不止几个。AspectJ令代码更精简,结构更良好.