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"/>