Spring Aop面向切面编程前置通知举例

1、Spring框架一般都是基于 AspectJ 实现 AOP 操作,AspectJ 不是 Spring 组成部分,独立 AOP 框架,一般把 AspectJ 和 Spirng 框架一起使 用,进行 AOP 操作

2.、基于 AspectJ 实现 AOP 操作

(1)基于 xml 配置文件实现

(2)基于注解方式实现(使用)

3、引入相关依赖

http://pan.baidu.com/s/1z35cpopnjISXSd29TAlXUQ?pwd=8080

提取码:8080

4.切入点表达式

(1)切入点表达式作用:知道对哪个类里面的哪个方法进行增强

(2)语法结构: execution([权限修饰符] [返回类型] [类全路径] [方法名称]([参数列表]) )

举例execution(* com.xxs.Aop.User.add(..))

*代表所有权限类型 返回类型可省略,但是权限修饰符和全类名之间需要加空格,add为需要增强的方法名 (..)为参数列表可以多个

AOP

1.创建普通方法类

package com.xxs.Aop;

import org.springframework.stereotype.Component;

import java.sql.SQLOutput;

@Component
public class User {
    public void add(){
        System.out.println("add............");
    }
}

2.创建增强方法(此方法为切入方法加上@Aspect注解),前置通知加上@Before

package com.xxs.Aop;

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


@Component
@Aspect
public class Users {
    //前置通知
    @Before(value = "execution(* com.xxs.Aop.User.add(..))")
    public void addPluse(){
        System.out.println("ADD......");
    }
}

3.配置xml注解扫描,当扫描到包下有@Aspect注解时自动创建该类再通过方法上的注解确定通知类型

<?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">
    <context:component-scan base-package="com.xxs.Aop"></context:component-scan>
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

</beans>

4.创建test方法测试是否在方法调用前执行

package com.xxs.Aop;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class test1 {
    @Test
    public void test(){
        ApplicationContext context =new ClassPathXmlApplicationContext("bean1.xml");
        User user = context.getBean("user", User.class);//这里使用注解扫描,s默认为该类的名字首字母小写
        user.add();
    }
}

这里简单举例AOP通知的前置通知,还有后置,环绕,异常,最终通知,在不影响本来的代码下引入更多的方法,这种方法降低耦合度,使得代码能够实现高内聚低耦合

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值