一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Spring框架实现AOP两种方式代码解析

时间:2022-09-05 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下Spring框架实现AOP两种方式代码解析,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

第一种AOP实现方式

AfterLog

package com.xxx.demo.service1;

import org.junit.After;
import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {
    @Override
    //returnValue:返回值
    public void afterReturning(Object returnValue, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println(
                "执行了"+method.getName()+"返回的结果:"+returnValue
        );
    }
}

Log

package com.xxx.demo.service1;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

//前置通知
public class log implements MethodBeforeAdvice {
    @Override
    //method:要执行的目标对象的方法 args:参数 target:目标读写
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

配置文件

applicationContext.xml





    
    
    



    
        
        


        
        
    

实例调用

package com.xxx.demo.service1;

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

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理代理的是接口
        UserService userService =(UserService) context.getBean("userService");
        userService.add();
        userService.delete();
        userService.select();
        userService.update();
    }
}

定义接口

package com.xxx.demo.service1;

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

    @Override
    public void delete() {
        System.out.println("删除了一个用户");
    }

    @Override
    public void update() {
        System.out.println("更新了一个用户");
    }

    @Override
    public void select() {
        System.out.println("查询了一个用户");
    }
}

第二种AOP实现方式





    
    
    

    
    

        

            

            
            
        
    

热门栏目