栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringAOP基本操作

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringAOP基本操作

首先创建一个Maven Web项目

 

 

 

 最后点击finish mavenweb项目就创建好了

创建好后src/main下不存在java和resources文件夹需要手动创建

 设置好后在pom.xml中导入spring和aspectjweaver依赖

Aop需要spring-aop和aspectjweaver依赖支持

    
      org.springframework
      spring-webmvc
      5.2.0.RELEASE
    
    
      commons-logging
      commons-logging
      1.2
    
    
      org.aspectj
      aspectjweaver
      1.9.4
    

创建applicationContext.xml配置service的bean



    

 

        

创建service层模拟一个添加方法

package com.wang.service;

public interface UserService {
    public void add();
}
package com.wang.service.impl;

import com.wang.service.UserService;

public class UserServiceImpl implements UserService {
    @Override
    public void add() {
        System.out.println("增加了一个用户");

    }
}

在applicationContext.xml中加入aop的注解支持并注册AnnotationPointCut的bean


    
    

创建一个AnnotationPointCut类

package com.wang.diy;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

//方式三:使用注解方式实现AOP
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {

    @Before("execution(* com.wang.service.impl.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("方法执行前");
    }
    @After("execution(* com.wang.service.impl.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("方法执行后");
    }
    //在环绕增强中,可以给定一个参数,代表要获取处理切入的点
    @Around("execution(* com.wang.service.impl.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        Signature signature = jp.getSignature();//获得签名
        System.out.println("执行了"+signature+"方法");
        //执行方法
        Object proceed = jp.proceed();
        System.out.println("返回的结果为:"+proceed);
        System.out.println("环绕后");
    }
}

创建一个测试AOP类

package com.wang;

import com.wang.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestAOP {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }
}

测试成功

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/754360.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号