11520171026


11520171026
1、Spring框架提供五个增强方位实现 [增强方位 + 增强逻辑代码]

1)、Before() org.apringframework.aop.MethodBeforeAdvice
2)、After-returning(返回后) org.springframework.aop.AfterReturningAdvice
3)、After-throwing(抛出后) org.springframework.aop.ThrowsAdvice
4)、Arround(周围) org.aopaliance.intercept.MethodInterceptorWeaving
5)、Introduction(引入) org.springframework.aop.IntroductionInterceptor

2、基于代理实现AOP编程步骤?

1)、编写一个类实现于增强方位接口

2)、写工厂代理方法

//代理工厂类
ProxyFactory pf=new ProxyFactory();
pf.setTarget(目标对象);
//添加增强类(增强方位+增强逻辑代码)
pf.addAdvice(advice);
//获取代理实例
pf.getProxy();

3、增强控制粒度(目标类下所有方法)

4、AOP 所做事情的本质:将公共的业务(如日志、安全、事务管理等)和领域业务结合,当执行领域业务时将公共业务横切加进来。实现公共业务的重复利用,领域业务更加纯粹,程序员可以专心于领域业务,本质就是动态代理package com.tiger.advice;

import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.stereotype.Component;
/**
* 后置逻辑增强
* @author tiger
* @date 2017年10月26日
*/
@Component
public class AfterAdvice implements AfterReturningAdvice {
/**
* 目标方法执行后执行的通知
* @param returnValue--返回值
* @param method 被调用的方法对象
* @param args 被调用的方法对象的参数
* @param target 被调用的方法对象的目标对象
* */
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("[AfterAdvice:]Welcom to you next time!");
}
}
package com.tiger.advice;

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.stereotype.Component;
/**
* 前置逻辑增强
* @date 2017年10月26日
*/
@Component
public class BeforeAdvice implements MethodBeforeAdvice {
/**
* @param method 被调用方法的对象
* @param agrs 被调用的方法的参数
* @param target 被调用方法的目标对象
*/
@Override
public void before(Method method, Object[] agrs, Object target) throws Throwable {
System.out.println("[BeforeAdvice:]how are you!");
}
}
package com.tiger.advice;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* 环绕逻辑增强
* @author tiger
* @date 2017年10月26日
*/
public class SurroundAdvice implements MethodInterceptor {

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
//前置增强逻辑
System.out.println("[SurroundAdvice:]how are you!");
/**
* 目标核心方法
*/
Object result = invocation.proceed();
//后置增强逻辑
System.out.println("[SurroundAdvice:]Welcom to you next time!");
return result;
}
}
package com.tiger.main;

import org.springframework.aop.framework.ProxyFactory;

import com.tiger.advice.BeforeAdvice;
import com.tiger.bean.Waiter;
/**
* 测试
* @author tiger
* @date 2017年10月26日
*/
public class Main {

public static void main(String[] args) {

Waiter waiter = new Waiter();
BeforeAdvice beforeAdvice = new BeforeAdvice();

ProxyFactory proxyFactory = new ProxyFactory();

//注入目标代理类对象
proxyFactory.setTarget(waiter);

//注入增强类(增强方位+增强逻辑代码)
proxyFactory.addAdvice(beforeAdvice);

//获取代理实例
waiter = (Waiter) proxyFactory.getProxy();

//方法调用
waiter.greet("李老板");
// waiter.offWork();

}
}