大家好!
我正在学习 Spring,文档说所有 @Repository 类异常都将自动转换为 DataAccessException。
用户存储库:
package org.example.dao;
public interface UserDAO {
void addUser(User user);
}
@Repository
public class UserDAOImpl implements UserDAO {
public void addUser(User user) {
throw new HibernateException("unchecked exception");
}
}
用户服务:
package org.example.services;
public interface UserService {
void addUser(User user);
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDAO userDAO;
@Override
public void addUser(User user) {
try {
userDAO.addUser(user);
} catch (Exception e) {
e.printStackTrace();
}
}
}
在 web.xml 中:
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
实际上我得到了一个 HibernateException。我不明白异常翻译是如何工作的。为什么 HibernateException 没有转换为 DataAccessException 类型的异常?
谁能告诉我我误解了什么?:)
原来我错过了主要细节:在配置中指定异常的实现
org.springframework.dao.support.PersistenceExceptionTranslator。概括:
org.springframework.dao.support.PersistenceExceptionTranslator@Repository谢谢大家!