12. AOP学习

1.Spring AOP简介

AOP (Aspect Oriented Programming)面向切面编程
OOP(Oriented Oriented Programming)面向对象编程
通过OOP的纵向和AOP的横向抽取,程序才可以真正解决问题
AOP的使用场景:日志 事务

2.AOP的核心概念

  • Aspect(切面)
  • Join Point(连接点)
  • Advice(通知/增强)
  • Pointcut(切点)
  • Introduction(引入)
  • Target Object(目标对象)
  • AOP Proxy(AOP代理)
  • Weaving(织入)

3.HelloWorld前置增强练习

  • 给pom文件中添加aop依赖
 
    
      org.springframework
      spring-aop
      ${spring.version}
    
    
    
      org.aspectj
      aspectjrt
      ${aspectj.version}
    
    
      org.aspectj
      aspectjweaver
      ${aspectj.version}
    
  • Hello接口类
package com.spring.aop;
public interface Hello {
    String getHello();
}
  • HelloImpl类
package com.spring.aop;
public class HelloImpl implements Hello {
    @Override
    public String getHello() {
        return "Hello,Spring AOP";
    }
}
  • 用户自定义的前置增强类MyBeforeAdvicelei
package com.spring.aop;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*
 * 用户自定义的前置增强类
 * */
public class MyBeforeAdvice {
    private  static final Logger logger= LoggerFactory.getLogger(MyBeforeAdvice.class);
    /*定义前置方法*/
    public void beforeMethod() {
        logger.info("This is a before method by wxy");
        logger.debug("This is a before method by wxy");
      //System.out.println("This is a before methoad");
    }
}

用日志记录方法

  • 配置文件
     
     
      
      
    
    
        
            
            
        
    
  • HelloApp主类
package com.spring.aop;
import javafx.application.Application;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("/bean.xml");
        Hello hello = context .getBean(Hello.class);
        System.out.println(hello.getHello());
    }
}

  • 运行结果

你可能感兴趣的:(12. AOP学习)