spring-aop学习笔记一

一、用spring的aop在一个方法前打印日志

方法接口:

public interface AitihmeticCalculator {

    int add(int i, int j);
    int sub(int i, int j);
    int mul(int i, int j);
    int div(int i, int j);
}

实现接口:

@Component
public class AitihmeticCalculatorImpl implements AitihmeticCalculator{
    @Override
    public int add(int i, int j) {
        int resulet = i+j;
        return resulet;
    }

    @Override
    public int sub(int i, int j) {
        int resulet = i-j;
        return resulet;
    }

    @Override
    public int mul(int i, int j) {
        int resulet = i*j;
        return resulet;
    }

    @Override
    public int div(int i, int j) {
        int resulet = i/j;
        return resulet;
    }
}

这里基于注解的方式来实现aop  所以用@Component这个注解来声明一个bean

二、日志切面

//把这个类声明为一个切面 需要把该类放到ioc容器当中
@Aspect
@Component
public class LoggingAspect {

    //声明该方法是一个前置通知
    @Before("execution(public int com.spring.spring.impl.AitihmeticCalculator.add(int,int))")
    public void beforeMethod(JoinPoint joinPoint){
        List<Object> args = Arrays.asList(joinPoint.getArgs());
    }
}
@Before("execution()")

前置通知 execution可执行方法

三、配置文件

<?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:p="http://www.springframework.org/schema/p"
       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-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

        <!--配置自动扫描的包-->
        <context:component-scan base-package="com.spring.spring.impl"></context:component-scan>

        <!--使AspjectJ 注解起作用:自动匹配的类生成代理对象-->
        <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
1.spring AOP

1)加入jar包
aspectjweaver-1.9.1.jar
commons-logging-1.2.jar
spring-aop-4.3.18.RELEASE.jar
spring-aspects-4.3.18.RELEASE.jar
spring-beans-4.3.18.RELEASE.jar
spring-context-4.3.18.RELEASE.jar
spring-core-4.3.18.RELEASE.jar
spring-expression-4.3.18.RELEASE.jar

2)在配置文件中加入aop的命名空间

①基于注解的方式  在配置文件中加入如下配置
 <!--使AspjectJ 注解起作用:自动匹配的类生成代理对象-->
 <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

②把横切关注点的代码抽象到切面类中
i.切面首先是一个ioc的bean  即@Component注解
ii 切面还需要加入 @Aspect注解

③在类中声明各种通知
i 声明一个方法
ii 在方法前加入@Before注解

④可以在声明方法中声明一个类型为JoinPoint的参数 然后就能访问链接细节  如方法名称方法参数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值