spring之AOP理解

面向切面编程实际实际上就是动态代理。看图:
这里写图片描述
Target:目标类,需要被增强的类,也就是上面我们写的UserServiceImpl。
JointPoint:连接点,目标类上需要被增强的方法,(这些方法可以被增强,也可以不增强,也就是说目标类中所有的方法都可以称为是连接点)
PointCut:切入点,被增强的方法(已经确定这个方法要被增强),切入点就是一个连接点的子集
Advice:增强/通知,增强的代码,也就是上面将增强的代码凑成的一个类。类中的每个方法都代表一个增强的功能代码,这个类中的方法就被称为通知
weaving:织入,将切入点和通知结合,从没被增强到已经增强的过程
Aspect:切面,切入点和通知结合,切入点 和 通知点 多点形成面

UserServiceImpl.java(目标)

package nuc.test.aop;

public class UserServiceImpl {
    public void add() {//(切点)
        System.out.println("spring add");
    }
}

MySpect.java(通知)

package nuc.test.aop;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class MySpect implements MethodInterceptor{

    public Object invoke(MethodInvocation invocation) throws Throwable {
        // TODO Auto-generated method stub
        System.out.println("前");
        Object obj = invocation.proceed();
        System.out.println("后");
        return obj;
    }


}

beans-aop.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd ">

   <!-- bean definition & AOP specific configuration -->
   <bean id="userServiceImplId" class="nuc.test.aop.UserServiceImpl"/>
   <bean id="mySpect" class="nuc.test.aop.MySpect"/>

   <aop:config>
      <aop:pointcut expression="execution(* nuc.test.aop.UserServiceImpl.*(..))" id="myPoint"></aop:pointcut>
      <aop:advisor advice-ref="mySpect" pointcut-ref="myPoint"></aop:advisor>
   </aop:config>
</beans

MainApp.java

package nuc.test.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
      ApplicationContext ac = new ClassPathXmlApplicationContext("beans-aop.xml");
      UserServiceImpl u =(UserServiceImpl) ac.getBean("userServiceImplId") ;
      u.add();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

涛涛之海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值