|
| 1 | +**正文** |
| 2 | + |
| 3 | +我们知道在面向对象OOP编程存在一些弊端,当需要为多个不具有继承关系的对象引入同一个公共行为时,例如日志,安全检测等,我们只有在每个对象里引入公共行为,这样程序中就产生了大量的重复代码,所以有了面向对象编程的补充,面向切面编程(AOP),AOP所关注的方向是横向的,不同于OOP的纵向。接下来我们就详细分析下spring中的AOP。首先我们从动态AOP的使用开始。 |
| 4 | + |
| 5 | +## AOP的使用 |
| 6 | + |
| 7 | +在开始前,先引入Aspect。 |
| 8 | + |
| 9 | +```xml |
| 10 | +<!-- aspectjweaver --> |
| 11 | +<dependency> |
| 12 | + <groupId>org.aspectj</groupId> |
| 13 | + <artifactId>aspectjweaver</artifactId> |
| 14 | + <version>${aspectj.version}</version> |
| 15 | +</dependency> |
| 16 | +``` |
| 17 | + |
| 18 | +### 创建用于拦截的bean |
| 19 | + |
| 20 | +```java |
| 21 | +public class TestBean { |
| 22 | + private String message = "test bean"; |
| 23 | + |
| 24 | + public String getMessage() { |
| 25 | + return message; |
| 26 | + } |
| 27 | + |
| 28 | + public void setMessage(String message) { |
| 29 | + this.message = message; |
| 30 | + } |
| 31 | + |
| 32 | + public void test(){ |
| 33 | + System.out.println(this.message); |
| 34 | + } |
| 35 | +} |
| 36 | +``` |
| 37 | + |
| 38 | + |
| 39 | + |
| 40 | +### 创建Advisor |
| 41 | + |
| 42 | +Spring中摒弃了最原始的繁杂配置方式而采用@AspectJ注解对POJO进行标注,使AOP的工作大大简化,例如,在AspectJTest类中,我们要做的就是在所有类的test方法执行前在控制台beforeTest。而在所有类的test方法执行后打印afterTest,同时又使用环绕的方式在所有类的方法执行前后在此分别打印before1和after1,以下是AspectJTest的代码: |
| 43 | + |
| 44 | +```java |
| 45 | +@Aspect |
| 46 | +public class AspectJTest { |
| 47 | + @Pointcut("execution(* *.test(..))") |
| 48 | + public void test(){ |
| 49 | + } |
| 50 | + |
| 51 | + @Before("test()") |
| 52 | + public void beforeTest(){ |
| 53 | + System.out.println("beforeTest"); |
| 54 | + } |
| 55 | + |
| 56 | + @Around("test()") |
| 57 | + public Object aroundTest(ProceedingJoinPoint p){ |
| 58 | + System.out.println("around.....before"); |
| 59 | + Object o = null; |
| 60 | + try{ |
| 61 | + o = p.proceed(); |
| 62 | + }catch(Throwable e){ |
| 63 | + e.printStackTrace(); |
| 64 | + } |
| 65 | + System.out.println("around.....after"); |
| 66 | + return o; |
| 67 | + } |
| 68 | + |
| 69 | + @After("test()") |
| 70 | + public void afterTest() |
| 71 | + { |
| 72 | + System.out.println("afterTest"); |
| 73 | + } |
| 74 | + } |
| 75 | +``` |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | +### 创建配置文件 |
| 80 | + |
| 81 | +要在Spring中开启AOP功能,,还需要在配置文件中作如下声明: |
| 82 | + |
| 83 | +```xml |
| 84 | +<?xml version="1.0" encoding="UTF-8" ?> |
| 85 | +<beans xmlns="http://www.springframework.org/schema/beans" |
| 86 | + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| 87 | + xmlns:context="http://www.springframework.org/schema/context" |
| 88 | + xmlns:aop="http://www.springframework.org/schema/aop" |
| 89 | + xsi:schemaLocation="http://www.springframework.org/schema/beans |
| 90 | + http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> |
| 91 | + |
| 92 | + <aop:aspectj-autoproxy/> |
| 93 | + <bean id="test" class="com.dabin.myspring.demo.aop.TestBean"> |
| 94 | + <property name="message" value="这是一个苦逼的程序员"/> |
| 95 | + </bean> |
| 96 | + <bean id="aspect" class="com.dabin.myspring.demo.aop.AspectJTest"/> |
| 97 | +</beans> |
| 98 | +``` |
| 99 | + |
| 100 | + |
| 101 | + |
| 102 | +### 测试 |
| 103 | + |
| 104 | +```java |
| 105 | +public class Test { |
| 106 | + public static void main(String[] args) { |
| 107 | + ApplicationContext bf = new ClassPathXmlApplicationContext("aspectTest.xml"); |
| 108 | + TestBean bean = (TestBean)bf.getBean("test"); |
| 109 | + bean.test(); |
| 110 | + } |
| 111 | +} |
| 112 | +``` |
| 113 | + |
| 114 | + |
| 115 | + |
| 116 | +执行后输出如下: |
| 117 | + |
| 118 | + |
| 119 | + |
| 120 | + |
| 121 | + |
| 122 | +Spring实现了对所有类的test方法进行增强,使辅助功能可以独立于核心业务之外,方便与程序的扩展和解耦。 |
| 123 | + |
| 124 | +那么,Spring是如何实现AOP的呢?首先我们知道,SPring是否支持注解的AOP是由一个配置文件控制的,也就是`<aop:aspectj-autoproxy/>`,当在配置文件中声明了这句配置的时候,Spring就会支持注解的AOP,那么我们的分析就从这句注解开始。 |
| 125 | + |
| 126 | + |
| 127 | + |
| 128 | +## AOP自定义标签 |
| 129 | + |
| 130 | +之前讲过Spring中的自定义注解,如果声明了自定义的注解,那么就一定会在程序中的某个地方注册了对应的解析器。我们搜索 **aspectj-autoproxy** 这个代码,尝试找到注册的地方,全局搜索后我们发现了在org.springframework.aop.config包下的AopNamespaceHandler中对应着这样一段函数: |
| 131 | + |
| 132 | +```java |
| 133 | +@Override |
| 134 | +public void init() { |
| 135 | + // In 2.0 XSD as well as in 2.1 XSD. |
| 136 | + registerBeanDefinitionParser("config", new ConfigBeanDefinitionParser()); |
| 137 | + registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser()); |
| 138 | + registerBeanDefinitionDecorator("scoped-proxy", new ScopedProxyBeanDefinitionDecorator()); |
| 139 | + |
| 140 | + // Only in 2.0 XSD: moved to context namespace as of 2.1 |
| 141 | + registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser()); |
| 142 | +} |
| 143 | +``` |
| 144 | + |
| 145 | +这里我们就不再对spring中的自定义注解方式进行讨论了。从这段代码中我们可以得知,在解析配置文件的时候,一旦遇到了aspectj-autoproxy注解的时候会使用解析器AspectJAutoProxyBeanDefinitionParser进行解析,接下来我们就详细分析下其内部实现。 |
| 146 | + |
| 147 | +### 注册AnnotationAwareAspectJAutoProxyCreator |
| 148 | + |
| 149 | +所有解析器,因为都是对BeanDefinitionParser接口的统一实现,入口都是从parse函数开始的,AspectJAutoProxyBeanDefinitionParser的parse函数如下: |
| 150 | + |
| 151 | +```java |
| 152 | +@Override |
| 153 | +@Nullable |
| 154 | +public BeanDefinition parse(Element element, ParserContext parserContext) { |
| 155 | + // 注册AnnotationAwareAspectJAutoProxyCreator |
| 156 | + AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element); |
| 157 | + // 对于注解中子类的处理 |
| 158 | + extendBeanDefinition(element, parserContext); |
| 159 | + return null; |
| 160 | +} |
| 161 | +``` |
| 162 | + |
| 163 | +通过代码可以了解到函数的具体逻辑是在registerAspectJAnnotationAutoProxyCreatorIfecessary方法中实现的,继续进入到函数体内: |
| 164 | + |
| 165 | +```java |
| 166 | +/** |
| 167 | + * 注册AnnotationAwareAspectJAutoProxyCreator |
| 168 | + * @param parserContext |
| 169 | + * @param sourceElement |
| 170 | + */ |
| 171 | +public static void registerAspectJAnnotationAutoProxyCreatorIfNecessary( |
| 172 | + ParserContext parserContext, Element sourceElement) { |
| 173 | + // 注册或升级AutoProxyCreator定义beanName为org.springframework.aop.config.internalAutoProxyCreator的BeanDefinition |
| 174 | + BeanDefinition beanDefinition = AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary( |
| 175 | + parserContext.getRegistry(), parserContext.extractSource(sourceElement)); |
| 176 | + // 对于proxy-target-class以及expose-proxy属性的处理 |
| 177 | + useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement); |
| 178 | + // 注册组件并通知,便于监听器做进一步处理 |
| 179 | + registerComponentIfNecessary(beanDefinition, parserContext); |
| 180 | +} |
| 181 | +``` |
| 182 | + |
| 183 | +在registerAspectJAnnotationAutoProxyCreatorIfNeccessary方法中主要完成了3件事情,基本上每行代码都是一个完整的逻辑。接下来我们详细分析每一行代码。 |
| 184 | + |
| 185 | +#### 注册或升级AnnotationAwareAspectJAutoProxyCreator |
| 186 | + |
| 187 | +对于AOP的实现,基本上都是靠AnnotationAwareAspectJAutoProxyCreator去完成,它可以根据@Point注解定义的切点来自动代理相匹配的bean。但是为了配置简便,Spring使用了自定义配置来帮助我们自动注册AnnotationAwareAspectJAutoProxyCreator,其注册过程就是在这里实现的。我们继续跟进到方法内部: |
| 188 | + |
| 189 | +```java |
| 190 | +public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, |
| 191 | + @Nullable Object source) { |
| 192 | + return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source); |
| 193 | +} |
| 194 | + |
| 195 | +public static final String AUTO_PROXY_CREATOR_BEAN_NAME = "org.springframework.aop.config.internalAutoProxyCreator"; |
| 196 | + |
| 197 | +private static BeanDefinition registerOrEscalateApcAsRequired(Class<?> cls, BeanDefinitionRegistry registry, |
| 198 | + @Nullable Object source) { |
| 199 | + |
| 200 | + Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); |
| 201 | + //如果已经存在了自动代理创建器且存在的自动代理创建器与现在的不一致那么需要根据优先级来判断到底需要使用哪个 |
| 202 | + if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) { |
| 203 | + BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME); |
| 204 | + if (!cls.getName().equals(apcDefinition.getBeanClassName())) { |
| 205 | + int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName()); |
| 206 | + int requiredPriority = findPriorityForClass(cls); |
| 207 | + if (currentPriority < requiredPriority) { |
| 208 | + //改变bean最重要的就是改变bean所对应的className属性 |
| 209 | + apcDefinition.setBeanClassName(cls.getName()); |
| 210 | + } |
| 211 | + } |
| 212 | + return null; |
| 213 | + } |
| 214 | + //注册beanDefinition,Class为AnnotationAwareAspectJAutoProxyCreator.class,beanName为internalAutoProxyCreator |
| 215 | + RootBeanDefinition beanDefinition = new RootBeanDefinition(cls); |
| 216 | + beanDefinition.setSource(source); |
| 217 | + beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE); |
| 218 | + beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); |
| 219 | + registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition); |
| 220 | + return beanDefinition; |
| 221 | +} |
| 222 | +``` |
| 223 | + |
| 224 | +以上代码实现了自动注册AnnotationAwareAspectJAutoProxyCreator类的功能,同时这里还涉及了一个优先级的问题,如果已经存在了自动代理创建器,而且存在的自动代理创建器与现在的不一致,那么需要根据优先级来判断到底需要使用哪个。 |
| 225 | + |
| 226 | +### 处理proxy-target-class以及expose-proxy属性 |
| 227 | + |
| 228 | +useClassProxyingIfNecessary实现了proxy-target-class属性以及expose-proxy属性的处理,进入到方法内部: |
| 229 | + |
| 230 | +```java |
| 231 | +private static void useClassProxyingIfNecessary(BeanDefinitionRegistry registry, @Nullable Element sourceElement) { |
| 232 | + if (sourceElement != null) { |
| 233 | + //实现了对proxy-target-class的处理 |
| 234 | + boolean proxyTargetClass = Boolean.parseBoolean(sourceElement.getAttribute(PROXY_TARGET_CLASS_ATTRIBUTE)); |
| 235 | + if (proxyTargetClass) { |
| 236 | + AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry); |
| 237 | + } |
| 238 | + //对expose-proxy的处理 |
| 239 | + boolean exposeProxy = Boolean.parseBoolean(sourceElement.getAttribute(EXPOSE_PROXY_ATTRIBUTE)); |
| 240 | + if (exposeProxy) { |
| 241 | + AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry); |
| 242 | + } |
| 243 | + } |
| 244 | +} |
| 245 | +``` |
| 246 | + |
| 247 | +在上述代码中用到了两个强制使用的方法,强制使用的过程其实也是一个属性设置的过程,两个函数的方法如下: |
| 248 | + |
| 249 | +```java |
| 250 | +public static void forceAutoProxyCreatorToUseClassProxying(BeanDefinitionRegistry registry) { |
| 251 | + if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) { |
| 252 | + BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME); |
| 253 | + definition.getPropertyValues().add("proxyTargetClass", Boolean.TRUE); |
| 254 | + } |
| 255 | +} |
| 256 | + |
| 257 | +public static void forceAutoProxyCreatorToExposeProxy(BeanDefinitionRegistry registry) { |
| 258 | + if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) { |
| 259 | + BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME); |
| 260 | + definition.getPropertyValues().add("exposeProxy", Boolean.TRUE); |
| 261 | + } |
| 262 | +} |
| 263 | +``` |
| 264 | + |
| 265 | + |
| 266 | + |
| 267 | +proxy-target-class:Spring AOP部分使用JDK动态代理或者CGLIB来为目标对象创建代理。(建议尽量使用JDK的动态代理),如果被代理的目标对象实现了至少一个接口, 則会使用JDK动态代理。所有该目标类型实现的接口都将被代理。若该目标对象没有实现任何接口,则创建一个CGLIB代理。如果你希望强制使用CGLIB代理,(例如希望代理目标对象的所有方法,而不只是实现自接口的方法)那也可以。但是需要考虑以下两个问题。 |
| 268 | + |
| 269 | +1. 无法通知(advise) Final方法,因为它们不能被覆写。 |
| 270 | +2. 你需要将CGLIB二进制发行包放在classpath下面。 |
| 271 | + |
| 272 | +与之相较,JDK本身就提供了动态代理,强制使用CGLIB代理需要将<aop:config>的 proxy-target-class 厲性设为 true: |
| 273 | + |
| 274 | +``` |
| 275 | +<aop:config proxy-target-class = "true">...</aop:config> |
| 276 | +``` |
| 277 | + |
| 278 | +当需要使用CGLIB代理和@AspectJ自动代理支持,可以按照以下方式设罝<aop:aspectj- autoproxy>的 proxy-target-class 属性: |
| 279 | + |
| 280 | +``` |
| 281 | +<aop:aspectj-autoproxy proxy-target-class = "true"/> |
| 282 | +``` |
| 283 | + |
| 284 | +- JDK动态代理:其代理对象必须是某个接口的实现,它是通过在运行期间创建一个接口的实现类来完成对目标对象的代理。 |
| 285 | +- CGIJB代理:实现原理类似于JDK动态代理,只是它在运行期间生成的代理对象是针对目标类扩展的子类。CGLIB是高效的代码生成包,底层是依靠ASM (开源的Java字节码编辑类库)操作字节码实现的,性能比JDK强。 |
| 286 | +- expose-proxy:有时候目标对象内部的自我调用将无法实施切面中的增强,如下示例: |
| 287 | + |
| 288 | +```java |
| 289 | +public interface AService { |
| 290 | + public void a(); |
| 291 | + public void b(); |
| 292 | +} |
| 293 | + |
| 294 | +@Service() |
| 295 | +public class AServicelmpll implements AService { |
| 296 | + @Transactional(propagation = Propagation.REQUIRED) |
| 297 | + public void a() { |
| 298 | + this.b{); |
| 299 | + } |
| 300 | + |
| 301 | + @Transactional(propagation = Propagation.REQUIRES_NEW) |
| 302 | + public void b() { |
| 303 | + } |
| 304 | +} |
| 305 | +``` |
| 306 | + |
| 307 | +此处的this指向目标对象,因此调用this.b()将不会执行b事务切面,即不会执行事务增强, 因此 b 方法的事务定义“@Transactional(propagation = Propagation.REQUIRES_NEW)” 将不会实施,为了解决这个问题,我们可以这样做: |
| 308 | + |
| 309 | +``` |
| 310 | +<aop:aspectj-autoproxy expose-proxy = "true"/> |
| 311 | +``` |
| 312 | + |
| 313 | +然后将以上代码中的 “this.b();” 修改为 “((AService) AopContext.currentProxy()).b();” 即可。 通过以上的修改便可以完成对a和b方法的同时增强。 |
0 commit comments