美文网首页
Day03:AOP

Day03:AOP

作者: 宇宙超人喵学长 | 来源:发表于2017-07-27 14:47 被阅读0次

1、横切

  • 连接点:应用通知的所有点
  • 通知:切面是什么及何时使用
  • 切点:通知被应用的具体位置(哪些连接点)
  • 切面:通知和切点的结合

2、Spring的AOP

2.1 AOP支持类型

  • 基于代理的经典Spring AOP
  • 纯POJO切面
  • @AspectJ注解驱动的切面
  • 注入式AspectJ切面

前三中,构建在动态代理的基础上,只支持方法拦截

2.1.1 经典Spring AOP

笨重复杂,直接使用ProxyFactoryBean

2.1.2 POJO切面

  • 使用@Aspect注解类,在方法上注解,同时该类也是普通的类
    @Before("execution(* concert.Performance.perform(..))")
    方法上,每个方法都需要切点表达式
    还包括 @After、 @AfterReturning、 @AfterThrowing、 @Around[通知方法将目标方法封装起来]、 @Before
  • 通过 @ Poingcut 注解定义命名的切点,然后调用
    @Poingcut("execution(** concert.Performance.perform(..))") public void performace(){} @Before("performance()")

2.2 配置类级别的自动代理

2.2.1在JavaConfig中,注解

@Configuration @EnableAspectJAutoProxy @ComponentScan

2.2.2 xml中配置

  • 引入aop命名空间 xmlns:aop="http://www.springframework.org/schema/aop" xml:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aopsoring-aop.xsd
  • <aop:aspectj-autoproxy /> <bean class="concert.Audidence" />

2.3 环绕通知

  • 示例,使用 @Around 注解
    `@Around("performance()")
    public void wtachPerformance(ProceddingJoinPoint jp) {
    jp.proceed();//不调用会阻塞被通知方法的调用

}`

2.4 带参数的通知

`@Poingcut("execution(** soundsystem.CompactDisc.playTrack(int)) && args(trackNumber) ")
public void trackPlayed(int trackNumber){}

@Before("trackPlayed(trackNumber)")
public void countTrack(int trackNumber) {
//修改trackNumber的值
}`
//表达式分解:
*:返回任意类型
soundsystem.CompactDise:方法所属的类型
playTrack(int)) :方法及接受的参数类型
args(trackNumber) :指定参数

3、注解加新功能

3.1 添加新的方法(接口)

给现有的bean添加接口,通过代理暴露新接口,该方法被调用时,代理将此调用委托给实现了新接口的其他对象
@Aspect public class EncoreableIntroducer { @DeclareParents(value="concert.Performance+", defaultImpl=DefaultEncorealbe.class) public static Encoreable encoreable; }
//解释说明
value:指定要引入该接口的bean,+代表它的所有子类型,不是它本身
defaultImpl:引入功能的实现类
@DeclareParents注解:要引入的接口

相关文章

网友评论

      本文标题:Day03:AOP

      本文链接:https://www.haomeiwen.com/subject/gddnkxtx.html