美文网首页
12. AOP学习

12. AOP学习

作者: 叶小慈呀 | 来源:发表于2019-03-09 22:47 被阅读0次

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依赖
 <!--spring-aop依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--aspectj依赖-->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>${aspectj.version}</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>${aspectj.version}</version>
    </dependency>
  • 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");
    }
}

用日志记录方法

  • 配置文件
     <!--配置一个Hello的bean  等同于Hello hello = new HelloImpl();-->
     <bean id="hello" class="com.spring.HelloImpl"/>
      <!--配置一个MyBeforeAdvice前置增强的bean-->
      <bean id="mybeforeAdvice" class="com.spring.MyBeforeAdvice"/>
    <!--配置Aop-->
    <aop:config>
        <aop:aspect id="before" ref="mybeforeAdvice">
            <aop:pointcut id="myPointcut" expression="execution(* com.spring.aop.*.*(..))"/>
            <aop:before method="beforeMethod" pointcut-ref="myPointcut"/>
        </aop:aspect>
    </aop:config>
  • 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学习

      本文链接:https://www.haomeiwen.com/subject/umhypqtx.html