spring五种通知类型(一)

2014-11-24 09:21:59 · 作者: · 浏览: 13
3. 通知类型 **
1) 前置通知
在目标方法调用 前执行。丌能阻止后续执行,除非抛异常
2) 后置通知
在目标方法调用 后执行。目标方法正常结束才执行。
3) 最终通知
在目标方法调用 后执行。目标方法正常戒异常都执行。
4) 异常通知
在目标方法调用发生异常 后执行。
5) 环绕通知
在目标方法调用 前和 后执行。
这5种类型的通知,在内部调用时这样组织
try{
调用前置通知
环绕前置处理
调用目标对象方法
环绕后置处理
调用后置通知
}catch(Exception e){
调用异常通知
}finally{
调用最终通知
}
【案例2】使用通知类型 **
1) 使用工程spring2
2) 前置通知
a. 新建AopBean
[java]
package tarena.aop;
public class AopBean {
//前置通知方法
public void mybefore(){
System.out.println("--前置通知--");
}
}
b. 修改aop.xml
[java]
< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
expression="within (tarena.service.*)" />
c. 新建Test1
[java]
package tarena.service;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test1 {
private static final String CONFIG = "aop.xml";
/**
* @param args
*/
public static void main(String[] args) {
try{
ApplicationContext ac =
new ClassPathXmlApplicationContext(CONFIG);
UserService userService =
(UserService)ac.getBean("userservice");
userService.update();
userService.save();
userService.delete();
}catch(Exception e){
}
}
}
d. 运行Test
3) 后置通知
a. 修改AopBean
[java]
package tarena.aop;
public class AopBean {
//前置通知方法
public void mybefore(){
System.out.println("--前置通知--");
}
//后置通知方法
public void myafterReturning(){
System.out.println("--后置通知--");
}
}
b. 修改aop.xml
[java]
class="tarena.service.UserServiceImpl">
expression="within (tarena.service.*)" />
pointcut-ref="servicepointcut"/>
pointcut-ref="servicepointcut"/>
c. 运行Test1
需要注意的是:
如上是正常执行程序情况下,会提示通知;如果目标方法出现异常,将丌会执行后置通知
接下来我们添加一些异常,模拟出现异常状况
d. 修改UserServiceImpl
[java]
package tarena.service;
public class UserServiceImpl implements UserService {
public void delete() {
System.out.println("删除用户信息");
//模拟NullPointException
String s = null;
s.length();
}
public void save() {
System.out.println("保存用户信息");
}
public void update() {
System.out.println("更新用户信息");
}
}
e. 运行Test
后置通知是在运行目标方法执行成功后调用的,如果目标方法执行失败(出现异常),
后置通知将丌被调用
除此特点外,后置通知可以得到目标方法的返回值
f. 修改UserServiceImpl
[java]
package tarena.service;
public class UserServiceImpl implements UserService {
public void delet