aop-例子

该博客介绍了如何使用注解来实现AOP(面向切面编程),包括定义要切入的接口及其实现类,详细说明了切入点方法,并提供了XML配置文件的示例,最后展示了测试代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用注解实现AOP

要切入的接口

package service;

public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void query();

}

其具体实现类

package service;

import service.UserService;

public class UserServiceImpl 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 query() {
        System.out.println("查询了一个用户");
    }
}

切入方法:

package diy;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

//方式三:使用注解方式实现aop


//标注这个类是一个切面
@Aspect
public class AnnotationPointCut {
    @Before("execution(* service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("========方法执行前======================");
    }

    @After("execution(* service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("==========方法执行后=========================");
    }

}

xml配置文件

<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        ">
        <!--注册bean-->
    <bean id="userService" class="service.UserServiceImpl"/>
    <bean id="BeforeLog" class="log.BeforeLog"/>
    <bean id="AfterLog" class="log.AfterLog"/>

    <!--方式3-->
    <bean id="annotationPointCut" class="diy.AnnotationPointCut"/>
    <!--开启注解支持-->
    <aop:aspectj-autoproxy/>
 </beans> 

测试代码:

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值