Spring框架学习第五讲(AOP操作——注解实现)

一、 基于AspectJ的注解实现AOP操作

1.1 导入Spring基本JAR包

1.2 创建被增强类和增强类

  1. 被增强类Book,实例注解方式创建Book Bean
package com.spring.annotationAOP;
import org.springframework.stereotype.Component;

@Component("book")
public class Book {
    public void add(){
        System.out.println("book add...");
    }
}
  1. 增强类Mybook,实例注解方式创建Book Bean

  2. 在增强类上需要添加@Aspect注解

  3. 在增强的方法上需要添加下面五种注解声明通知方法
    • @Before – 前置增强
    • @Before – 后置增强
    • @AfterReturning – 后置增强
    • @AfterThrowing –抛出异常后增加
    • @Around –前后增强
package com.spring.annotationAOP;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("myBook")
@Aspect
public class Mybook {
    @Autowired
    private Book book;

    @After("execution(* com.spring.annotationAOP.Book.*(..))")
    //使用注解方式,表达式添加切入点
    public void afterAdd(){
        System.out.println("mybook add...");
    }
}

1.3 配置Spring核心文件bean3.xml

  1. 需要开启AOP自动代理
  2. 需要添加相应的schema约束(aop,context)
<?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" 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"> <!-- bean definitions here -->

    <!-- 开启注解扫描,在包里面扫描类、方法、属性上面是否有注解 -->
    <context:component-scan base-package="com.spring.annotationAOP"></context:component-scan>

    <!-- 开启AOP自动代理 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

1.4 测试代码

package test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.annotationAOP.Book;

public class AOPannotationTest {
    @Test
    public void testAopAnnotation(){
        ApplicationContext context = new ClassPathXmlApplicationContext("aopAnnotation.xml");
        Book book = (Book) context.getBean("book");
        book.add();
    }
}

1.5 输出结果

book add...
mybook add...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值