AspectJ全注解

发布于 2021-08-25  42 次阅读


package com.apesblog;

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

@Configuration
@ComponentScan(basePackages = {"com.apesblog"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class SpringConfig {

}
package com.apesblog;

import org.springframework.stereotype.Component;

@Component
public class User {
     public void add(){
         System.out.println("add");
     }

}
package com.apesblog;

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

@Component
@Aspect
public class UserProxy {
    @Before(value = "execution(* com.apesblog.User.*(..))")
    public void before(){
        System.out.println("before");
    }
}
package com.apesblog;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Test {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
        User user = applicationContext.getBean("user", User.class);
        user.add();
    }
}