import org.aspectj.lang.JoinPoint;
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;
//告诉spring进行扫描
@Component
//告诉Spring 这个类为切入类
@Aspect
public class LogAdvice {
//切入点表达式
@Pointcut("execution(* 需要切入的类的路径.*(..))")
public void aspect(){
}
//前置通知
@Before("aspect()")
public void beforeLog(JoinPoint joinPoint){
System.out.println("LogAdvice before");
}
//后置通知
@After("aspect()")
public void afterLog(JoinPoint joinPoint){
System.out.println("LogAdvice after");
}
}
创建一个新类
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
//告诉Spring这是一个配置类
@Configuration
//开启Spring 对aspect的支持
@EnableAspectJAutoProxy
//扫描整个项目
@ComponentScan("com.example")
public class AnnotationAppConfig {
}
入口类
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AnnotationAppConfig.class);
////记得在配置类中注入Bean
VideoService videoService = (VideoService) context.getBean("videoService");
videoService.findById(2);
}
配置类
import com.example.service.VideoService;
import com.example.service.impl.VideoServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
VideoService videoService(){
return new VideoServiceImpl();
}
}