最近工做中我都是基于注解实现AOP功能,经常使用的开启AOP的注解是@EnableAspectJAutoProxy,咱们就从它入手。
java
AnnotationAwareAspectJAutoProxyCreator查看其中文注释(以下),肯定它就是AOP的核心类!--温安适 20191020spring
/**
1.AspectJAwareAdvisorAutoProxyCreator的子类
,用于处理当前应用上下文中的注解切面
2.任何被AspectJ注解的类将自动被识别。
3.若SpringAOP代理模式能够识别,优先使用Spring代理模式。
4.它覆盖了方法执行链接点
5.若是使用<aop:include>元素,
则只有名称与include模式匹配的@aspectj bean才被视为切面
,并由spring自动代理。
6. Spring Advisors的处理请查阅,
org.springframework.aop
.framework.autoproxy.AbstractAdvisorAutoProxyCreator
*/
@SuppressWarnings("serial")
public class AnnotationAwareAspectJAutoProxyCreator
extends AspectJAwareAdvisorAutoProxyCreator {
//...省略实现
}注解切面
复制代码
虽然找到了核心类,可是并无找到核心方法!下面咱们尝试画类图肯定核心方法。缓存
AnnotationAwareAspectJAutoProxyCreator的部分类图。
bash
//AbstractAutoProxyCreator中的postProcessAfterInitialization实现
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (!this.earlyProxyReferences.contains(cacheKey)) {
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
复制代码
发现发现疑似方法wrapIfNecessary,查看其源码以下,发现createProxy方法。肯定找对了地方。ide
protected Object wrapIfNecessary
(Object bean, String beanName, Object cacheKey) {
if (beanName != null && this.targetSourcedBeans.contains(beanName)) {
return bean;
}
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
return bean;
}
if (isInfrastructureClass(bean.getClass())
|| shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
// 建立代理
Object[] specificInterceptors =
getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
Object proxy = createProxy(
bean.getClass(), beanName,
specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
复制代码
即AnnotationAwareAspectJAutoProxyCreator实现BeanPostProcessor的postProcessAfterInitialization方法,在该方法中由wrapIfNecessary实现了AOP的功能。 wrapIfNecessary中有2个和核心方法post
查看源码以下,默认实如今AbstractAdvisorAutoProxyCreator中。ui
@Override
@Nullable
protected Object[] getAdvicesAndAdvisorsForBean(
Class<?> beanClass, String beanName,
@Nullable TargetSource targetSource) {
List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
if (advisors.isEmpty()) {
return DO_NOT_PROXY;
}
return advisors.toArray();
}
复制代码
查阅findEligibleAdvisors方法,就干了3件事this
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
//找全部加强器
List<Advisor> candidateAdvisors = findCandidateAdvisors();
//找全部匹配的加强器
List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
extendAdvisors(eligibleAdvisors);
if (!eligibleAdvisors.isEmpty()) {
//排序
eligibleAdvisors = sortAdvisors(eligibleAdvisors);
}
return eligibleAdvisors;
}
复制代码
AnnotationAwareAspectJAutoProxyCreator 重写了findCandidateAdvisors,下面咱们看看具体实现了什么spa
@Override
protected List<Advisor> findCandidateAdvisors() {
// Add all the Spring advisors found according to superclass rules.
List<Advisor> advisors = super.findCandidateAdvisors();
// Build Advisors for all AspectJ aspects in the bean factory.
if (this.aspectJAdvisorsBuilder != null) {
//@Aspect注解的类在这里除了
advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
}
return advisors;
}
复制代码
从该方法咱们能够看到处理@Aspect注解的bean的方法是:this.aspectJAdvisorsBuilder.buildAspectJAdvisors()。 这个方法以下:.net
public List<Advisor> buildAspectJAdvisors() {
List<String> aspectNames = this.aspectBeanNames;
if (aspectNames == null) {
synchronized (this) {
aspectNames = this.aspectBeanNames;
if (aspectNames == null) {
List<Advisor> advisors = new ArrayList<>();
aspectNames = new ArrayList<>();
//找到全部BeanName
String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.beanFactory, Object.class, true, false);
for (String beanName : beanNames) {
if (!isEligibleBean(beanName)) {
continue;
}
// 必须注意,bean会提早暴露,并被Spring容器缓存,可是这时还不能织入。
Class<?> beanType = this.beanFactory.getType(beanName);
if (beanType == null) {
continue;
}
if (this.advisorFactory.isAspect(beanType)) {
//找到全部被@Aspect注解的类
aspectNames.add(beanName);
AspectMetadata amd = new AspectMetadata(beanType, beanName);
if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
MetadataAwareAspectInstanceFactory factory =
new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
//解析封装为Advisor返回
List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory);
if (this.beanFactory.isSingleton(beanName)) {
this.advisorsCache.put(beanName, classAdvisors);
}
else {
this.aspectFactoryCache.put(beanName, factory);
}
advisors.addAll(classAdvisors);
}
else {
// Per target or per this.
if (this.beanFactory.isSingleton(beanName)) {
throw new IllegalArgumentException("Bean with name '" + beanName +
"' is a singleton, but aspect instantiation model is not singleton");
}
MetadataAwareAspectInstanceFactory factory =
new PrototypeAspectInstanceFactory(this.beanFactory, beanName);
this.aspectFactoryCache.put(beanName, factory);
advisors.addAll(this.advisorFactory.getAdvisors(factory));
}
}
}
this.aspectBeanNames = aspectNames;
return advisors;
}
}
}
if (aspectNames.isEmpty()) {
return Collections.emptyList();
}
List<Advisor> advisors = new ArrayList<>();
for (String aspectName : aspectNames) {
List<Advisor> cachedAdvisors = this.advisorsCache.get(aspectName);
if (cachedAdvisors != null) {
advisors.addAll(cachedAdvisors);
}
else {
MetadataAwareAspectInstanceFactory factory = this.aspectFactoryCache.get(aspectName);
advisors.addAll(this.advisorFactory.getAdvisors(factory));
}
}
return advisors;
}
复制代码
这个方法能够归纳为:
众所周知,建立代理的经常使用的2种方式是:JDK建立和CGLIB,下面咱们就看看这2中建立代理的例子。
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JDKProxyMain {
public static void main(String[] args) {
JDKProxyTestInterface target = new JDKProxyTestInterfaceImpl();
// 根据目标对象建立代理对象
JDKProxyTestInterface proxy =
(JDKProxyTestInterface) Proxy
.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new JDKProxyTestInvocationHandler(target));
// 调用代理对象方法
proxy.testProxy();
}
interface JDKProxyTestInterface {
void testProxy();
}
static class JDKProxyTestInterfaceImpl
implements JDKProxyTestInterface {
@Override
public void testProxy() {
System.out.println("testProxy");
}
}
static class JDKProxyTestInvocationHandler
implements InvocationHandler {
private Object target;
public JDKProxyTestInvocationHandler(Object target){
this.target=target;
}
@Override
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
System.out.println("执行前");
Object result= method.invoke(this.target,args);
System.out.println("执行后");
return result;
}
}
复制代码
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class CglibProxyTest {
static class CglibProxyService {
public CglibProxyService(){
}
void sayHello(){
System.out.println(" hello !");
}
}
static class CglibProxyInterceptor implements MethodInterceptor{
@Override
public Object intercept(Object sub, Method method,
Object[] objects, MethodProxy methodProxy)
throws Throwable {
System.out.println("before hello");
Object object = methodProxy.invokeSuper(sub, objects);
System.out.println("after hello");
return object;
}
}
public static void main(String[] args) {
// 经过CGLIB动态代理获取代理对象的过程
Enhancer enhancer = new Enhancer();
// 设置enhancer对象的父类
enhancer.setSuperclass(CglibProxyService.class);
// 设置enhancer的回调对象
enhancer.setCallback(new CglibProxyInterceptor());
// 建立代理对象
CglibProxyService proxy= (CglibProxyService)enhancer.create();
System.out.println(CglibProxyService.class);
System.out.println(proxy.getClass());
// 经过代理对象调用目标方法
proxy.sayHello();
}
}
复制代码
类型 | jdk建立动态代理 | cglib建立动态代理 |
---|---|---|
原理 | java动态代理是利用反射机制生成一个实现代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理 | cglib动态代理是利用asm开源包,对代理对象类的class文件加载进来,经过修改其字节码生成子类来处理 |
核心类 | Proxy 建立代理利用反射机制生成一个实现代理接口的匿名类InvocationHandler 方法拦截器接口,须要实现invoke方法 | net.sf.cglib.proxy.Enhancer:主要加强类,经过字节码技术动态建立委托类的子类实例net.sf.cglib.proxy.MethodInterceptor:方法拦截器接口,须要实现intercept方法 |
局限性 | 只能代理实现了接口的类 | 不能对final修饰的类进行代理,也不能处理final修饰的方法 |
Spring的选择选择如何代理时在DefaultAopProxyFactory 中。
public class DefaultAopProxyFactory implements AopProxyFactory,
Serializable {
@Override
public AopProxy createAopProxy(AdvisedSupport config)
throws AopConfigException {
if (config.isOptimize()
|| config.isProxyTargetClass()
|| hasNoUserSuppliedProxyInterfaces(config)) {
Class<?> targetClass = config.getTargetClass();
if (targetClass == null) {
throw new AopConfigException(
"TargetSource cannot determine target class: "
+"Either an interface or a target "+
" is required for proxy creation.");
}
if (targetClass.isInterface()
|| Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}
//...
}
复制代码
//exposeProxy=true AopContext 能够访问,proxyTargetClass=true CGLIB生成代理 @EnableAspectJAutoProxy(exposeProxy=true,proxyTargetClass=true)
总结下Spring如何选择建立代理的方式:
Spring如何实现AOP?,您能够这样说: