11、AOP
11.1、什么是AOP
11.2、Aop在Spring中的作用
提供声明式事务,允许用户自定义切面
11.3、使用Spring实现Aop
【重点】使用AOP注入,需要导入一个依赖包!
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
方式一:使用Spring的API接口【主要SpringAPI接口实现】
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理代理的使接口
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
public class Log implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
//object:参数
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
public class AfterLog implements AfterReturningAdvice {
//returnValue 返回值
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
// returnValue="荣哥";
System.out.println("执行了"+method.getName()+"返回结果为:"+returnValue);
}
}
方式二:自定义实现AOP【主要是切面定义】
<!-- 方式二:自定义类-->
<bean id="diy" class="com.kuang.diy.DiyPoint"/>
<aop:config>
<!-- 自定义切面,ref 要引用的类-->
<aop:aspect ref="diy">
<!-- 切入点-->
<aop:pointcut id="point" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
<!-- 通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
方式三:使用注解实现
<!-- 开启注解支持! JDK(默认 proxy-target-class="false") cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy proxy-target-class="false"/>