用AOP捕捉 Service中调用Dao的异常

来源:互联网 发布:手机版淘宝的新品上架 编辑:程序博客网 时间:2024/06/06 03:50

PersonDao和PersonDaoImpl,并在PersonDaoImpl中制造异常


public interface PersonDao {public void savePerson();public void updatePerson();}


public class PersonDaoImpl implements PersonDao {public void savePerson() {int a = 1/0;}public void updatePerson() {Long.parseLong("aaa");}}

目标类和目标方法


public interface PersonService {void savePerson();void updatePerson();}

public class PersonServiceImpl implements PersonService {private PersonDao personDao;//在这里选择set方式在spring的配置文件中进行注入public PersonDao getPersonDao() {return personDao;}public void setPersonDao(PersonDao personDao) {this.personDao = personDao;}public void savePerson() {personDao.savePerson();}public void updatePerson() {personDao.updatePerson();}}


切面(定义一个异常类和异常方法)


public class Exception {/** * 这是一个异常通知 */public void exceptionMethod(JoinPoint joinPoint,Throwable ex){System.out.println(ex.getMessage());}}


配置文件

<?xml version="1.0" encoding="UTF-8"?>  <beans xmlns="http://www.springframework.org/schema/beans"         xmlns:aop="http://www.springframework.org/schema/aop"         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             http://www.springframework.org/schema/aop              http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">                <bean id="personDao" class="com.mo.dao.PersonDaoImpl"></bean>             <bean id="personService" class="com.mo.service.PersonServiceImpl">    <!-- 用set方法注入 -->    <property name="personDao" ref="personDao"></property>    </bean>          <bean id="Exception" class="com.mo.exception.Exception"></bean>          <aop:config>          <!-- 切入点表达式,确定目标类 -->          <aop:pointcut               expression="execution(* com.mo.service.PersonServiceImpl.*(..))"               id="perform"/>                        <!-- ref指向的对象就是切面 -->          <aop:aspect ref="Exception">               <aop:after-throwing method="exceptionMethod" pointcut-ref="perform" throwing="ex"/>          </aop:aspect>      </aop:config>  </beans>


单元测试类

@Testpublic void test(){        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");          PersonService personService = (PersonService)context.getBean("personService");        personService.savePerson();}


输出

/ by zero




0 0
原创粉丝点击