AOP注解

Demo:

package com.itheima.demo1;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

//加载xml配置文件
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo1 {
    
    @Resource(name="customerDao")
    private CustomerDao customerDao;
    
    @Test
    public void run(){
        customerDao.save();
        customerDao.update();
    }
}

切面类:

package com.itheima.demo1;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

/**
 * 注解方式的切面类
 * @author Administrator
 */

@Aspect
public class MyAspectAnno {
    /**
     * 通知类型:@Before前置通知(切入点表达式)
     * 
     * value里面的参数是execution(public * 想加入类的全路径.想加入方法的名字)
     */
    @Before(value="execution(public * com.itheima.demo1.CustomerDaoImpl.save())")
    public void log(){
        System.out.println("记录日志...");
    }
}

类:

package com.itheima.demo1;

public class CustomerDaoImpl implements CustomerDao {

    public void save() {
        System.out.println("保存客户...");
    }

    public void update() {
        System.out.println("修改客户...");
    }

}

配置文档:

<?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:context="http://www.springframework.org/schema/context"
    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.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    
    
    <!-- 开启自动代理,只有开启自动代理,注解的方式才会生效 -->
    <aop:aspectj-autoproxy/>
    <!-- 配置的是目标类 -->
    <bean id="customerDao" class="com.itheima.demo1.CustomerDaoImpl"></bean>


    <!-- 配置切面类 -->
    <bean id="myAspectAnno" class="com.itheima.demo1.MyAspectAnno"/>
    
</beans>

 

 

* 添加切面和通知的注解
* @Aspect -- 定义切面类的注解

* 通知类型(注解的参数是切入点的表达式)
* @Before -- 前置通知
* @AfterReturing -- 后置通知
* @Around -- 环绕通知
* @After -- 最终通知
* @AfterThrowing -- 异常抛出通知

posted @ 2017-04-21 16:04  tidhy  阅读(157)  评论(0编辑  收藏  举报