/**
* dao 接口
* @author w7
*
*/
public interface PersonDao {
public void savePerson() throws Exception;
}
/**
* dao 接口实现
* @author w7
*
*/
public class PersonDaoImpl implements PersonDao{
public void savePerson() throws Exception{
int b = 0;
if(b!=0){
int a = 1/b;
}else{
//自定义异常
throw new MyException("不能除以0");
}
System.out.println("save person");
}
}
/**
* service 接口
* @author w7
*
*/
public interface PersonService {
public void savePerson() throws Exception;
}
service的实现做为 :目标类
/**
* service 实现
* @author w7
*
*/
public class PersonServiceImpl implements PersonService{
private PersonDao personDao;
public PersonDao getPersonDao() {
return personDao;
}
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
public void savePerson() throws Exception{
this.personDao.savePerson();
}
}
service的异常统一提取 :切面
/**
* 切面:service统一 异常处理
* @author w7
*
*/
public class ExceptionAspect {
public void throwingMethod(Throwable ex){
System.out.println(ex.getMessage());
}
}
/**
* 切面:service统一 异常处理
* @author w7
*
*/
public class MyException extends Exception{
public MyException(String msg) {
super(msg);
}
}
/**
* 浏览器访问层 action
* @author w7
*
*/
public class PersonAction {
private PersonService personService;
public void setPersonService(PersonService personService) {
this.personService = personService;
}
public void savePerson() throws Exception{
this.personService.savePerson();
}
}
<!--
把personDao,personService,personAction放入到spring容器中
-->
<bean id="personDao" class="com.itheima09.springaop.xml.ex.exception.dao.PersonDaoImpl"></bean>
<bean id="personService" class="com.itheima09.springaop.xml.ex.exception.service.PersonServiceImpl">
<property name="personDao">
<ref bean="personDao"/>
</property>
</bean>
<bean id="personAction" class="com.itheima09.springaop.xml.ex.exception.action.PersonAction">
<property name="personService">
<ref bean="personService"/>
</property>
</bean>
<!--
引入切面
-->
<bean id="exceptionAspect"
class="com.itheima09.springaop.xml.ex.exception.aspect.ExceptionAspect"></bean>
<aop:config>
<aop:pointcut
expression="execution(* com.itheima09.springaop.xml.ex.exception.service.*.*(..))"
id="perform"/>
//异常处理
<aop:aspect ref="exceptionAspect">
<aop:after-throwing method="throwingMethod" pointcut-ref="perform" throwing="ex"/>
</aop:aspect>
</aop:config>
/**
说明:
从配置中可以看出,把service层所有的类当成目标类,只要service层所有的类的
所有的方法抛出异常,则exceptionAspect中的异常通知就会获取到目标方法抛出的
异常,所以在这里异常通知就是用来处理异常的,而且只有一个方法。并且该切面和所
有的其他类都是松耦合的。
**/
@Test
public void testException() throws Exception{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonAction personAction = (PersonAction)context.getBean("personAction");
personAction.savePerson();
/**
* 结果:不能除以0 处理了自定义的异常
*/
}