current position:Home>Chapter XXVIII Aspect-Oriented Programming of AOP Configuration Based on Spring Annotations

Chapter XXVIII Aspect-Oriented Programming of AOP Configuration Based on Spring Annotations

2022-08-06 19:02:48LiuJia111222333

Section1SetSpring AOPAnnotation base preparation

Introduction: PresentationSpring AOPBasic preparation for annotations 

  • Declare Aspect Class@Aspect(Span): usually a class that can be definedPointcuts and Notifications
  • Configure pointcuts and notifications (Chapter 2 LogAdvice class)

Section2Set OnSpring AOPAnnotation Configuration and Scanning

Introduction: OnSpring AOPAnnotation and Scanning

  • EnableSpringAOPAnnotationConfiguration
@Configuration //Need to get an annotation configuration [email protected]("") //Scan packages below com is equivalent to the context.scan("") operation//Enable spring support for [email protected] class AnnotationAopConfiguration {//This is an AOP configuration class}

Aspect class: Component needs to be added, otherwise the file cannot be scanned

@Component //register [email protected] // Tell Spring that this is an aspect class, which can define pointcuts and advice methodspublic class LogAdvice { //Annotation completes the aspect function//define a [email protected](value = "execution(**(..))")public void PointCut(){ }//Define a [email protected]("PointCut()")public void before(){System.out.println("Pre-enhancement processing");}}

VideoService implementation class: also need to add Service annotation, otherwise the bean cannot be scanned

@Service("videoService")public class VideoServiceImpl implements VideoService {public int addOrder(VideoOrder videoOrder) {System.out.println("Use the addOrder method");return 0;}public Long delOrder(VideoOrder videoOrder) {System.out.println("Use the delOrder method");return null;}public List findOrderById() {System.out.println("Use the findOrderById method");return null;}public int updateOrder(VideoOrder videoOrder) {System.out.println("Use updateOrder method");return 0;}public int save(Video video) {System.out.println("Save a video");return 0;}}

Test class;Note that getBean is no longer an interface, but our AOP configuration class uses this, we do not need to write refresh operation, and scan operation, because in the configurationThe class has all been configured with annotations.

 /*** Use annotations to print log processing*/@Testpublic void Test3(){//1. Need to configure AOP configuration class//2. Use annotation to create contextAnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AnnotationAopConfiguration.class);//3. Get a bean in a configuration classVideoService videoService =(VideoService) context.getBean("videoService");//4. The execution method will be notified to cut in at the same timevideoService.addOrder(new VideoOrder());}

Running result:

copyright notice
author[LiuJia111222333],Please bring the original link to reprint, thank you.

Random recommended