运用Aop自定义注解

1、建一个注解接口类MyNote

package com.xiangwen.test.mynote;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Documented
@Retention(RUNTIME)
@Target(METHOD)
/**
 * 自定义注解
 */
public @interface MyNote {
}

2、定义一个切面类MyNoteImpl

package com.xiangwen.test.mynote;

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

/**
 * <h5>描述:通过@Aspect注解使该类成为切面类</h5>
 */
@Aspect
@Component
public class MyNoteImpl {
    @Pointcut("@annotation(com.xiangwen.test.mynote.MyNote)")
    private void cut() {
    }

    /**
     * <h5>功能:前置通知</h5>
     */
    @Before("cut()")
    public void before() {
        System.out.println("自定义注解生效了");
    }
}

3、建一个扫包类AppConfig

package com.xiangwen.test.mynote;

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

@Configuration
@ComponentScan( "com.xiangwen.test.mynote")
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class AppConfig {
}

4、建一个测试类加上自定义注解

package com.xiangwen.test.mynote;

import org.springframework.stereotype.Component;

@Component
public class Car {
    @MyNote//自定义注解
    public void running(){
        System.out.println("汽车跑起来了");
    }
}

5、运行

package com.xiangwen.test.mynote;

import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AppTest {
    @Test
    public void test1(){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        Car car = context.getBean("car",Car.class);
        car.running();
    }
}

 

6、结果

 

posted @ 2021-05-25 15:13  傲云萧雨  阅读(92)  评论(0编辑  收藏  举报