SpringAop四、开启AOP功能
先讲一下如何引入AOP功能 第一步就是引入包了,一般在Spring环境下首先需要依赖spring-context,而spring-context是引入了AOP的,因此一般spring环境是直接有aop的包依赖的。 第二步启用aop功能,常见3种方式:
-
使用springboot的情况下直接引入aop的starter即可 使用xml配置的形式,主配置文件中添加 <aop:aspectj-autoproxy/>
<xsd:element name="aspectj-autoproxy">
<xsd:annotation>
<xsd:documentation source="java:org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"><![CDATA[
Enables the use of the @AspectJ style of Spring AOP.
See org.springframework.context.annotation.EnableAspectJAutoProxy Javadoc
for information on code-based alternatives to this XML element.
]]></xsd:documentation>
...
</xsd:element>
-
使用注解方式,任意Configuration类中添加@EnableAspectJAutoProxy注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
// AOP动态代理注册器
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {
/**
* Indicate whether subclass-based (CGLIB) proxies are to be created as opposed
* to standard Java interface-based proxies. The default is {@code false}.
*/
boolean proxyTargetClass() default false;
/**
* Indicate that the proxy should be exposed by the AOP framework as a {@code ThreadLocal}
* for retrieval via the {@link org.springframework.aop.framework.AopContext} class.
* Off by default, i.e. no guarantees that {@code AopContext} access will work.
* @since 4.3.1
*/
boolean exposeProxy() default false;
}
@Nullable
public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(
BeanDefinitionRegistry registry, @Nullable Object source) {
return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
}
可以看到,不管是xml配置形式,还是@EnableAspectJAutoProxy注解形式,本质上都是注册了一个AnnotationAwareAspectJAutoProxyCreator处理器 我们再看一下springboot中 aop-starter的自动配置类:
@Configuration
@ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class,
AnnotatedElement.class })
@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
public class AopAutoConfiguration {
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = false)
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false", matchIfMissing = false)
public static class JdkDynamicAutoProxyConfiguration {
}
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", matchIfMissing = true)
public static class CglibAutoProxyConfiguration {
}
}
使用的@EnableAspectJAutoProxy注解,和注解方式一样。
关于@EnableAspectJAutoProxy注解补充一个知识点。使用的是Spring的@Import注解引入一个注册器,用于BeanDefinition的注册。这部分涉及到SpringIOC相关知识点,以后有机会补充。
后面章节详细介绍AnnotationAwareAspectJAutoProxyCreator处理器的执行过程。
至此,我们的环境已经设置完成,下面就是编写自己的Aspect类来实现AOP功能了。
