Spring的AOP应用

Spring的AOP也是常用功能功能之一使用该功能

使用AOP的功能仍然可以使用 注解与XML两种方式,这里我比较推荐xml方式配置,看着比较清晰,对于项目的配置文件,使用这种结构
这里写图片描述
将AOP的配置文件独立放置,然后使用一个xml文件引入;

1.使用xml配置AOP执行

    <aop:config>
        <aop:aspect id="audience" ref="audience">

            <!--配置com.spring.service包下所有类或接口的所有方法 -->
            <aop:pointcut id="performance"
                expression="execution(* com.houlu.SpringDemo.AOPInstance.Performer.*(..))" />

            <aop:before pointcut-ref="performance" method="takeSeats" />
            <aop:before pointcut-ref="performance" method="turnOffCellPhones" />
            <aop:after-returning pointcut-ref="performance"
                method="applaud" />
            <aop:after-throwing pointcut-ref="performance"
                method="demandRefund" />
        </aop:aspect>
    </aop:config>

在这里配置好之后就可以对应在com.houlu.SpringDemo.AOPInstance.Performer.*(..)这个类的包下执行AOP相关操作了

2.使用注解配置AOP执行

AOP同样也支持注解的执行方式,这里必须要打开的标签是

<aop:aspectj-autoproxy/> 

打开这段代码之后,AOP相关配置文件里面不许需写任何东西了,AOP的执行方法等内容可以直接配置到JAVA的代码段里,跟xml配制方法一样,此时定义在哪些包得哪些方法内部执行AOP相关操作;

package com.houlu.SpringDemo.AOPInstance;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 定义切面
 * @author lu.hou
 *
 */
@Component
@Aspect
public class Audience2 {

    @Pointcut("execution(* com.houlu.SpringDemo.AOPInstance.Performer.*(..))")
    public void anyMethod(){}

    @Before("anyMethod()")
    public void takeSeats(){
        System.out.println("注解方式执行 : The audience is taking their seats.");
    }
    @After("anyMethod()") 
    public void turnOffCellPhones(){
        System.out.println("注解方式执行 :The audience is turning off their cellphones");
    }
    public void applaud(){
        System.out.println("注解方式执行 :CLAP CLAP CLAP");
    }
    public void demandRefund(){
        System.out.println("注解方式执行 :Boo! We want money back");
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值