這篇文章將為大家詳細講解有關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為接口,在其中編寫需要使用的方法,主要是增(save)刪(delete)改(update)查(get&list–查詢全部)。 ②Xxx.java中的變量均為私有,并且與數據庫中的列名,屬性相同。
J2EE三層架構:


令DaoException繼承RuntimeException, 處理異常的時候可以將其拋給Service層(UserService.java),如果要處理那么就try,catch,否則就令其報錯

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>
單元測試類
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonService personService = (PersonService)context.getBean("personService");
personService.savePerson();
}輸出
/ by zero
關于“Service層講解DAO層中異常處理操作的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。