Spring AOP實例
AOP的一些概念:
切入點(Pointcut),在哪些類哪些方法上切入;
通知(Advice),在方法執行的什麼實際(when:方法前/方法後/方法前後)做什麼(what:增強的功能)
切面(Aspect),切面 = 切入點 + 通知,通俗點就是:在什麼時機,什麼地方,做什麼增強!
織入(Weaving),把切面加入到對象,並創建出代理對象的過程。(由 Spring 來完成)
繼續前文https://blog.csdn.net/qq_36328413/article/details/100176180
1.在 Packge【aspect】下準備日誌切面 【LoggerAspect】類:
package aspect;
import org.aspectj.lang.ProceedingJoinPoint;
public class LoggerAspect{
public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
//方法前
System.out.println("start log:" + joinPoint.getSignature().getName());
Object object = joinPoint.proceed();
//方法後
System.out.println("end log:" + joinPoint.getSignature().getName());
return object;
}
}
2.在 xml 文件中聲明業務對象和日誌切面:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean name="produceService" class="service.ProduceService" />
<bean id="loggerAspect" class="aspect.LoggerAspect"/>
<bean name="source" class="pojo.Source">
<property name="fruit" value="橙子"/>
<property name="sugar" value="多糖"/>
<property name="size" value="超大杯"/>
</bean>
<bean name="juiceMaker" class="pojo.juiceMaker">
<property name="source" ref="source" />
</bean>
<!-- 配置AOP -->
<aop:config>
<!-- where:在哪些地方(包.類.方法)做增加 -->
<aop:pointcut id="loggerCutpoint"
expression="execution(* pojo.juiceMaker.*(..)) "/>
<!-- what:做什麼增強 -->
<aop:aspect id="logAspect" ref="loggerAspect">
<!-- when:在什麼時機(方法前/後/前後) -->
<aop:around pointcut-ref="loggerCutpoint" method="log"/>
</aop:aspect>
</aop:config>
</beans>
3.創建測試類testaop
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.Source;
import pojo.juiceMaker;
import service.ProduceService;
public class testaop {
@SuppressWarnings("resource")
public static void main(String args[]){
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext2.xml");
Source source=(Source)context.getBean("source");
System.out.println(source.getFruit());
System.out.println(source.getSugar());
System.out.println(source.getSize());
juiceMaker juiceMaker=(juiceMaker)context.getBean("juiceMaker");
juiceMaker.makeJuice();
}
}
4.輸出結果如下