Spring AOP 基于注解的方式实现切面遍程

首先需要导入以下依赖

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>6.0.6</version>
    </dependency>
    <!-- spring核心 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.0.2.RELEASE</version>
    </dependency>

进行Spring配置类的声明

@ComponentScan  用于对文件中bean的扫描,类似于将bean加载到容器当中。
@Configuration用于声明这是一个配置类
@ComponentScan(value = "com.mingyu")用来扫描加载bean
@EnableAspectJAutoProxy用来开启我们的AOP注解,用于启动Spring AOP 的功能。
package com.mingyu.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@ComponentScan(value = "com.mingyu")
@Configuration
//用于开启AOP注解
@EnableAspectJAutoProxy
public class springConfig {
}

这是我们的功能增强类

@Aspect用于声明这个类是用于功能拓展的

@Pointcut()用于定义切点,即要对哪个函数进行功能增强。

package com.mingyu.aspect;

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

@Component
//用于定义一个切面(说明这个类是用于功能拓展的)
@Aspect
public class aspect {
    @Pointcut("execution(* com.mingyu.dao.*.*(..))" )
    public void blank(){}
    @Before("blank()")
    public void start(){
        System.out.println("before执行");
    }
    @After("blank()")
    public void after(){
        System.out.println("after执行");
    }
}

最后进行测试

import com.mingyu.aspect.aspect;
import com.mingyu.config.springConfig;
import com.mingyu.dao.studentDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(springConfig.class);
        studentDao sd = (studentDao) context.getBean("student");
        sd.study();
        sd.save();
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值