首页 > 技术文章 > spring之AspectJ基于xml AOP编程

pecool 2018-01-12 15:09 原文

一、引言:

  AspectJ框架不仅实现了面向切面编程,而且还支持注解,spring将它引入自己的规范之中。

二、需要了解:

 

  1. AspectJ是基于java语言的AOP框架
  2. spring2.0之后支持AspectJ切入点表达式
  3. 描述切点使用切入点表达式

三、通知的类型(重点)

 

四、利用AspectJ实现AOP计算代码执行时间戳

beans.xml文件

<!-- 目标类 -->
    <bean id="userDaoImpl" class="com.xx.dao.UserDaoImpl"></bean>
    <!-- 切面类 -->
    <bean id="myAspect" class="com.xx.dao.MyAspect"></bean>
    <!-- aop配置 -->    
    <aop:config>
        <!-- 配置切面
            <aop:aspect>:定义切面
            <aop:pointcut>:目标类中的切点,即连接点中的切点
            <aop:before>:通知类型共6种,分别为    前置、后置、环绕、异常、最终、引介
            method:切面中的方法
            pointcut-ref:引入切点
            pointcut :自定义切点,局限于当前
         -->
        <aop:aspect ref="myAspect">
            <aop:pointcut expression="execution(* com.xx.dao.UserDaoImpl.add*(..))" id="MyPointcut"/>
            <aop:before method="before" pointcut-ref="MyPointcut"/>
            <aop:after method="after" pointcut-ref="MyPointcut"/>
        </aop:aspect>
    </aop:config>

切面类:

package com.xx.dao;

public class MyAspect{

	private long beforeTime = 0;
	private long afterTime = 0;
	public void before(){
		beforeTime = System.currentTimeMillis();
	}
	public void after(){
		afterTime = System.currentTimeMillis();
		System.out.println("运行时间"+(afterTime-beforeTime));
	}
}

 

UserDao接口:

package com.xx.dao;

public interface UserDao {

	public void addUser();
	public void delUser();
	public void updateUser();
}

 UserDaoImpl实现类:

package com.xx.dao;

public class UserDaoImpl implements UserDao{

	@Override
	public void addUser() {
		System.out.println("增");
	}
	@Override
	public void delUser() {
		System.out.println("删");
	}
	@Override
	public void updateUser() {
		System.out.println("改");
	}
}

 测试类:

package com.xx.dao;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	public static void main(String[] args) {
		
		String xmlPath = "com/xx/dao/beans.xml";
		ApplicationContext context = new ClassPathXmlApplicationContext(xmlPath);
		UserDao userDao = (UserDao) context.getBean("userDaoImpl");
		userDao.addUser();
		userDao.delUser();
		userDao.updateUser();
	}
}

推荐阅读