结合Service层讲解DAO层的异常处理操作

网友投稿 792 2023-01-13

结合Service层讲解DAO层的异常处理操作

结合Service层讲解DAO层的异常处理操作

domain:只是定义一个javabean。

dao:对于数据库的操作,都放到dao层,也就是dao里面通常是对数据库的增、删、改、查等操作。

service:完成相应的业务逻辑处理,调用dao层。

(web)servlet:完成界面请求、对界面进行跳转等等。servlet调用service层。

例子:

在domain包中,新建Xxx.java;在dao包中,新建IXxxDAO.java;在impl包中,新建XxxDAOImpl类;在test包中,新建XxxDAOTest.java,在XxxDAOImpl.java中编写具体方法,核心步骤为“贾琏欲执事”。

注:

①IXxxDAO.java为接口,在其中编VEAItO写需要使用的方法,主要是增(save)删(delete)改(update)查(get&list–查询全部)。 ②Xxx.java中的变量均为私有,并且与数据库中的列名,属性相同。

J2EE三层架构:

令DaoException继承RuntimeException, 处理异常的时候可以将其抛给Service层(UserService.java),如果要处理那么就try,catch,否则就令其报错

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

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 PeVEAItOrsonDao 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());

}

}

配置文件

xmlns:aop="http://springframework.org/schema/aop"

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-2.5.xsd

http://springframework.org/schema/aop

http://springframework.org/schema/aop/spring-aop-2.5.xsd">

expression="execution(* com.mo.service.PersonServiceImpl.*(..))"

id="perform"/>

xmlns:aop="http://springframework.org/schema/aop"

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-2.5.xsd

http://springframework.org/schema/aop

http://springframework.org/schema/aop/spring-aop-2.5.xsd">

expression="execution(* com.mo.service.PersonServiceImpl.*(..))"

id="perform"/>

expression="execution(* com.mo.service.PersonServiceImpl.*(..))"

id="perform"/>

单元测试类

@Test

public void test(){

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

PersonService personService = (PersonService)context.getBean("personService");

personService.savePerson();

}

输出

/ by zero

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:银行小程序推送(中国银行更新信息微信小程序)
下一篇:小程序生态及应用(微信原生态小程序)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~