A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 牛江伟 中级黑马   /  2019-9-23 16:03  /  1179 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

1.AOP:面向切面编程
底层原理:基于jdk/基于cglib 的动态代理
技术 运行期 动态代理(不修改源码,增强目标;松耦合)  
oop:面向对象编程
隔离 业务逻辑(解耦合) 可重用性 开发效率
Aop拦截方法/接口
作用:在运行期间,在不修改源码的情况下对方法进行功能增强
优势:减少重复代码,提高开发效率,便于维护
配置文件:
切面:目标方法和增强方法结合

底层实现:spring提供的动态代理
jdk:接口(目标对象中实现了其接口的方法,代理对象也实现了接口的方法并且增强了此方法)
cglib:父类(代理对象继承了目标对象的方法,并增强了此方法)

Target(目标对象)
Proxy(代理)
Joinpoint(连接点):可以被增强的方法
pointcut(切入点):
advice(通知/增强):
aspect(切面):切点+通知
weaving(织入):

1.导入aspectjweaver的坐标
2.编写目标对象/切面
3.配置applicationContext.xml
*1.配置aop命名空间
*2.配置aop约束
*3.目标类
<bean id="target" class="com.itheima.aop.Target"></bean>
*4.切面类
<bean id="myAspect" class="com.itheima.aop.MyAspect"></bean>
*5织入(weaving)
<aop:config>
     <aop:aspect ref="myAspect">//声明myAspect的bean为切面类
          <aop:before method="before" pointcut="execution(public void com.itheima.aop.Target.method())"/>
      </aop:aspect>
</aop:config>
4测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest{
@Autowired
private TargetInterface target;
@Test
public void test(){
target.method();
}
}
切点表达式:
execution([修饰符] 返回值类型 包名.类名.方法名(参数))
*修饰符可以省略
*返回值类型 包名 类名 方法名 可以用*代替
*任意参数 ..
*当前包及其子包下的类 包名..类名

通知的类型:
1.前置通知<aop:before/>
2.后置通知<aop:after-returning/>
3.环绕通知<aop:around/>
4.异常抛出<aop:throwing/>   //目标方法异常后执行
5.最终通知<aop:after/>          //无论如何最后都要执行最终通知

//(ProceedingJoinPoint pjp):正在执行的连接点//切点
public Object around(ProceedingJoinPoint pjp){
sout("环绕前");
Object proceed = pjp.proceed();//切点方法
sout("环绕后");
return proceed;
}


切点表达式的抽取
<aop:pointcut id="myPonitcut" expression="execution(* com.itheima.aop.*.*(..))">
切点表达式的引用pointcut-ref="myPonitcut"
<aop:before method="增强方法名称" pointcut-ref="myPonitcut">

注解:
@Component("target")

@Component("myAspect")
@Aspect//标注当前类为切面类

@Before("execution(* com.itheima.anno.*.*(..))")

<context:component-Scan base-package="com.itheima"/>
<aop:aspectj-autoproxy/>//aop自动代理

注解抽取:
@Pointcut("execution(* com.itheima.anno.*.*(..))")
public void pointout(){}

@After("pointout()")
public void after(){
sout("后置通知....");
}

@Component("target")
@Component("myAspect")
@Aspect//标注当前类为切面类
@Before
@AfterReturning
@Around
@AfterTrowing
@After

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马