Srping中的增强类
Spring中的增强主要包括5种增强:前置增强、后置增强、环绕增强、异常增强、引介增强,除了引介增强其他都很好理解
Spring只支持方法级的增强,所以BeforeAdvice在Spring中的实现是MethodBeforeAdvice,增强代码如下:
public class WashBeforeEat implements MethodBeforeAdvice {
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println("饭前要洗手");
}
}
织入增强:
public class TestAdvice {
public static void main(String args[]){
Eat target = new myEat();
BeforeAdvice bf = new WashBeforeEat();
//Spring提供的工厂类
ProxyFactory pf = new ProxyFactory();
// pf.setInterfaces(target.getClass().getInterfaces());//指定接口采用JDK代理
// pf.setOptimize(true); //若启动优化,将继续采用cglib代理
//设置代理目标
pf.setTarget(target);
//为目标添加增强
pf.addAdvice(bf);
//生成代理实例
Eat proxy = (Eat) pf.getProxy();
proxy.eat("虾仁炒饭");
proxy.drink("绿豆汤");
}
}
其他增强方式大同小异
此处注意,若想指定采用JDK代理,则需要设置ProxyFactory的接口;若启动optimize优化,则会继续采用cglib代理,默认为false;
以SpringBean的方式实现增强如下
<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-3.0.xsd">
<bean id="beforeAdvice" class="aopTest.WashBeforeEat" />
<bean id="target" class="aopTest.myEat" />
<!-- 代理的接口 、代理的对象、使用的增强 -->
<bean id="eat" class="org.springframework.aop.framework.ProxyFactoryBean"
p:proxyInterfaces="aopTest.Eat"
p:target-ref="target"
p:interceptorNames="beforeAdvice"
p:proxyTargetClass="true"
p:singleton="true"
p:optimize="true"/>
</beans>
proxyInterfaces:代理要实现的接口;
target-ref:代理对象或者目标类;
interceptorNames:需要织入的增强,需要实现上面的那五个增强;
proxyTargetClass:对类进行代理,而不是对接口,所以设置为true时,proxyInterfaces将失效,将采用cglib代理;
singleton:返回的代理是否是单例模式,默认的是单例模式;
optimize:是否启用优化,设置为true时,强制使用cglib代理。
测试代码:
public class TestAutoProxy {
public static void main(String[] args) {
String path = "/aopTest/MyXml.xml";
@SuppressWarnings("resource")
ApplicationContext ctx = new ClassPathXmlApplicationContext(path);
Eat eat = (Eat) ctx.getBean("eat");
eat.drink("柠檬水");
}
}
输出:
饭前要洗手
今天喝柠檬水
参考文章:《Spring 3.x 企业应用开发实战》