public static void main(String[] args) {
//1、获取容器
AnnotationConfigApplicationContext
ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//2、获取Bean对象
UserService userService = ac.getBean(“userService”, UserService.class);
//3、准备数据
User user = new User();
user.setId(“1”);
user.setUsername(“test”);
user.setNickname(“张三”);
//4、执行方法
userService.update(user);
}
}
- 运行测试类(没有切入)
1、用于开启注解AOP支持
(1)@EnableAspectJAutoProxy
1)源码
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@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;
}
2)说明
作用:
表示开启spring对注解aop的支持。
它有两个属性,分别是指定采用的代理方式和
是否暴露代理对象,通过AopContext可以进行访问。
从定义可以看得出,它引入AspectJAutoProxyRegister.class
对象,该对象是基于注解@EnableAspectJAutoProxy
注册一个AnnotationAwareAspectJAutoProxyCreator
,该对象通过调用
AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
注册一个aop代理对象生成器。
关于AnnotationAwareAspectJAutoProxyCreator
请参
属性:
proxyTargetClass
:指定是否采用cglib进行代理。默认值是false,表示使用jdk的代理。
exposeProxy
: 指定是否暴露代理对象,通过AopContext
可以进行访问。
使用场景: 当我们注解驱动开发时,在需要使用aop
实现某些功能的情况下,都需要用到此注解。
3)示例
package cn.itbluebox.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan(“cn.itbluebox”)
@EnableAspectJAutoProxy
public class SpringConfiguration {
}
2、用于配置切面的
(1)@Aspect
1)源码
/**
-
Aspect declaration
-
@author Alexandre Vasseur
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Aspect {
/**
-
Per clause expression, defaults to singleton aspect
-
-
Valid values are “” (singleton), “perthis(…)”, etc
*/
public String value() default “”;
}
2)说明
作用:声明当前类是一个切面类。
属性:
value
:默认我们的切面类应该为单例的。但是当切面类为一个多例类时,指定预处理的切入点表达式。用法是perthis(切入点表达式)。
它支持指定切入点表达式,或者是用@Pointcut
修饰的方法名称(要求全限定方法名)
使用场景
:此注解也是一个注解驱动开发aop的必备注解。
3)示例
@Component
@Scope(“prototype”)//注意:通常情况下我们的切面类是不需要多例的。
@Aspect(value=“execution(* cn.itbluebox.service.impl..(…))”)
public class LogUtil {
/**
- 用于配置当前方法是一个前置通知
*/
@Before(“execution(* cn.itbluebox.service.impl..(…))”)
public void printLog(){
System.out.println(“执行打印日志的功能”);
}
}
3、用于配置切入点表达式的
(1)@Pointcut
1)源码
/**
-
Pointcut declaration
-
@author Alexandre Vasseur
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Pointcut {
/**
-
The pointcut expression
-
We allow “” as default for abstract pointcut