Spring AOP创建Throwdvice实例
程序员文章站
2023-11-04 11:34:52
1、异常发生的时候,通知某个服务对象做处理 2、实现throwsAdvice接口 接口实现: SayThrowAdvice文件: applicationContext.xml文件: 主方法文件: 执行效果: ......
1、异常发生的时候,通知某个服务对象做处理
2、实现throwsadvice接口
接口实现:
public interface ihello {
public void sayhello(string str) throws exception;
}
public class hello implements ihello {
@override
public void sayhello(string str) throws exception {
system.out.println("你好"+str);
//测试抛出异常
throw new exception("故意造成异常!");
}
}
saythrowadvice文件:
public class saythrowadvice implements throwsadvice {
public void afterthrowing(method method,object[] objs,object target,throwable ta)
{
system.out.println("我捕获的异常是-> "+ta+" =====, 在方法 "+method+"抛出了异常");
}
}
applicationcontext.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<!doctype beans public "-//spring//dtd bean 2.0//en"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!-- 建立目标对象实例 -->
<bean id="bean_hello" class="com.pb.hello" />
<!-- 创建执行前advice实例 -->
<bean id="sba" class="com.pb.saybeforeadvice" />
<!-- 创建执行后advice实例 -->
<bean id="sfa" class="com.pb.sayafteradvice" />
<!-- 创建around advice实例 -->
<bean id="ssd" class="com.pb.sayaroundadvice" />
<!-- 创建throw advice实例 -->
<bean id="sta" class="com.pb.saythrowadvice" />
<!-- 建立代理对象 -->
<bean id="helloproxy" class="org.springframework.aop.framework.proxyfactorybean">
<!-- 设置代理的接口 -->
<property name="proxyinterfaces">
<value>com.pb.ihello</value>
</property>
<!-- 设置目标对象实例 -->
<property name="target">
<ref bean="bean_hello"/>
</property>
<!-- 设置advice实例 -->
<property name="interceptornames">
<list>
<!--
<value>sba</value>
<value>sfa</value>
-->
<value>ssd</value>
<value>sta</value>
</list>
</property>
</bean>
</beans>
主方法文件:
public class maintest {
public static void main(string[] args) {
// todo auto-generated method stub
applicationcontext context=new classpathxmlapplicationcontext("applicationcontext.xml");
ihello hello=(ihello)context.getbean("helloproxy");
try {
hello.sayhello("访客");
} catch (exception e) {
// todo: handle exception
}
}
}
执行效果: