@Aspect创建简单切面

1.首先,要使用@Aspect注解需要引入依赖

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.0</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.9.0</version>
</dependency>

2.开启自动自动代理功能

2.1创建切面


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 MyAspect {

    @Pointcut("execution(* com.example.demo.TestController.getMessage(..))")
    public void perform(){

    }

    @Before("perform()")
    public void beforeRun(){
        System.out.println("before do it");
    }

}
package com;

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

@Configuration
//自动代理启用
@EnableAspectJAutoProxy
public class Config {
    @Bean
    public MyAspect aspect(){
        return new MyAspect();
    }
}

在执行com.example.demo.TestController.getMessage()方法之前都会先调用beforeRun方法。 

猜你喜欢

转载自blog.csdn.net/weixin_39102174/article/details/83013025
今日推荐