First example: AOP
1. Introduce the jars required by spring aop
aopalliance-1.0.jar
aspectjweaver.jar
cglib-nodep-2.1_3.jar
commons-logging-1.1.1.jar
servlet-api.jar
spring-aop-3.2.4.RELEASE.jar
spring-beans-3.2.4.RELEASE.jar
spring-context-3.2.4.RELEASE.jar
spring-core-3.2.4.RELEASE.jar
spring-expression-3.2.4.RELEASE.jar
2. Write the business interface and target class:
public interface UserService { publicvoidadd(String name); publicvoidselect(String name); } publicclassUserServiceImpl implementsUserService{ publicvoidadd (String name) { System.out.println("增加"+name+"..."); } publicvoid select(String name){ System.out.println("查询"+name+"..."); } } } |
3. Write a method to perform pre- and post-processing:
// Pre-enhancement : Indicates that the enhancement is implemented before the target method is executed publicclass BeforeAdvice implements MethodBeforeAdvice { @Override publicvoid before(Method arg0, Object[] arg1, Object arg2) throws Throwable { String clientName = (String)arg1[0]; System.out .println ( " Add a pointcut before executing the method ..." + arg1 ); } } |
Spring aop provides pre and post exception notification handling classes:
Notifications are divided into: pre-notification, post-notification, exception notification, final, surround notification
MethodBeforeAdvice ( pre-advice )
AfterReturningAdvice _ _ _
MethodInterceptor(前后通知)
ThrowsAdvice(异常通知)
4. Spring aop配置:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- 目标类 --> <bean id="target_1" class="com.aop.Waiter"/> <!-- 后置通知 --> <bean id="after" class="com.aop.AfterAdvice"></bean> <!-- 前置通知 --> <bean id="proxybean" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"> <!-- 接口接入 注入使用了接口,则使用JDK动态代理-> <value>com.aop.IWaiter</value> </property> <!-- 默认false使用jdk动态代理 <property name="proxyTargetClass" value="true"/> --> <property name="interceptorNames"> <list> <!-- 通知类引入 --> <value>before</value> <value>after</value> </list> </property> <!-- 注入要通知的目标类 --> <property name="target" ref="target_1"/> </bean> </beans>
|
Spring aop提供代理工厂bean,不用自己写,但是要指定属性注入要执行通知实现类。
<property name="proxyInterfaces"> 注入目标接口
<property name="interceptorNames"> 注入要通知的实现类列表
<property name="target" ref="target"/> 注入要通知的目标类
<property name="proxyTargetClass" value="true"/> 默认jdk代理
Spring AOP部分使用JDK动态代理或者CGLIB来为目标对象创建代理。
如果被代理的目标对象实现了至少一个接口,则会使用JDK动态代理。
如果该目标对象没有实现任何接口,则创建一个CGLIB代理。