说明
Spring使用增强类定义横向逻辑,同时Spring只支持方法连接点,增量类还包含在方法的哪一点添加横切代码的方位信息。所以增强既包含横向逻辑,又包含部分连接点的信息。
类型
按着增强在目标类方法的连接点位置,分为
- 前置增强
- 后置增强
- 环绕增强
- 异常抛出增强
- 引介增强
前置增强
场景:服务生提供2中服务:欢迎顾客、服务顾客
package com.jihite; public interface Waiter {
void greetTo(String name);
void serveTo(String name);
}
新来的服务生情况如下
package com.jihite; public class NaiveWaiter implements Waiter{
@Override
public void greetTo(String name) {
System.out.println("Greet to " + name);
} @Override
public void serveTo(String name) {
System.out.println("Serve to " + name);
}
}
新来的服务生上来就提供服务,比较生猛,在做每件事之前都改打个招呼,下面定义前置增强类
package com.jihite;
import org.springframework.aop.MethodBeforeAdvice; import java.lang.reflect.Method; public class GreetingBeforeAdvice implements MethodBeforeAdvice{
@Override
public void before(Method method, Object[] args, Object obj) throws Throwable {
String clientName = (String)args[0];
System.out.println("How are you! Mr." + clientName);
}
}
在Spring中配置
在src/main/resources中定义beans.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="greetingBeforeAdvice" class="com.jihite.GreetingBeforeAdvice"/>
<bean id="targetBefore" class="com.jihite.NaiveWaiter"/>
<bean id="waiterBefore" class="org.springframework.aop.framework.ProxyFactoryBean"
p:interceptorNames="greetingBeforeAdvice"
p:target-ref="targetBefore"
p:proxyTargetClass="true"
/>
</beans>
测试
public class BeforeAdviceTest {
private Waiter target;
private BeforeAdvice advice;
private ProxyFactory pf; @BeforeTest
public void init() {
target = new NaiveWaiter();
advice = new GreetingBeforeAdvice();
pf = new ProxyFactory();
pf.setTarget(target);
pf.addAdvice(advice);
}
}
结果
How are you! Mr.Jphn
Greet to Jphn
How are you! Mr.Tom
Serve to Tom
其他类型的增强类与前置增强类似,可参考代码