spring 常见异常
时间: 2023-10-28 09:22:59 浏览: 35
Spring 框架中常见的异常有:
1. NullPointerException:空指针异常,通常是因为调用了空对象的方法或属性,需要检查对象是否为空。
2. ClassNotFoundException:类未找到异常,通常是因为 classpath 中没有找到需要的类,需要检查类路径是否正确。
3. BeanCreationException:Bean 创建异常,通常是因为 Bean 创建过程中出现了错误,需要检查 Bean 的配置是否正确。
4. IllegalArgumentException:非法参数异常,通常是因为传递了不合法的参数,需要检查参数是否符合要求。
5. NoSuchBeanDefinitionException:Bean 定义未找到异常,通常是因为没有找到对应的 Bean 定义,需要检查 Bean 的名称是否正确。
6. InvalidPropertyException:属性不合法异常,通常是因为设置了不合法的 Bean 属性,需要检查属性是否正确。
7. IllegalStateException:状态异常,通常是因为对象的状态不符合要求,需要检查对象的状态是否正确。
8. TransactionException:事务异常,通常是因为事务处理过程中出现了错误,需要检查事务处理是否正确。
9. DataAccessException:数据访问异常,通常是因为数据库访问出现了错误,需要检查数据库配置是否正确。
10. SecurityException:安全异常,通常是因为安全检查失败,需要检查安全配置是否正确。
相关问题
springsecurity 异常处理
Spring Security提供了许多方式来处理身份验证和授权的异常。下面是一些常见的异常处理方式:
1. 使用Spring的全局异常处理器:可以通过在应用程序中定义一个`@ControllerAdvice`类,并使用`@ExceptionHandler`注解来处理Spring Security的异常。在异常处理方法中,可以根据不同的异常类型进行相应的处理,例如返回自定义的错误页面或者JSON响应。
```java
@ControllerAdvice
public class SecurityExceptionHandler {
@ExceptionHandler(AuthenticationException.class)
public ResponseEntity<String> handleAuthenticationException(AuthenticationException ex) {
// 处理身份验证异常
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ex.getMessage());
}
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<String> handleAccessDeniedException(AccessDeniedException ex) {
// 处理访问拒绝异常
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(ex.getMessage());
}
// 其他异常处理方法...
}
```
2. 自定义AccessDeniedHandler:可以实现`AccessDeniedHandler`接口来处理访问拒绝异常。可以在`handle()`方法中自定义处理逻辑,例如返回自定义的错误页面或者JSON响应。
```java
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex) throws IOException, ServletException {
// 处理访问拒绝异常
response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
}
}
```
然后,在Spring Security配置中指定自定义的`AccessDeniedHandler`:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// ...
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// ...
.exceptionHandling()
.accessDeniedHandler(new CustomAccessDeniedHandler())
// ...
}
// ...
}
```
这些只是处理Spring Security异常的两种常见方式,你可以根据实际需求选择适合的方式进行异常处理。
spring 常见面试题
以下是一些 Spring 常见面试题:
1. 什么是 Spring 框架?
2. Spring 框架有哪些核心模块?
3. Spring 的 IOC 是什么?
4. Spring 的 DI 是什么?
5. Spring 的 AOP 是什么?
6. Spring MVC 是什么?
7. Spring Boot 是什么?
8. Spring Cloud 是什么?
9. Spring 的事务管理是如何实现的?
10. Spring 的 Bean 生命周期是怎样的?
11. Spring 的 Bean 作用域有哪些?
12. Spring 中的注解有哪些?
13. Spring 中的 XML 配置有哪些?
14. Spring 如何集成其他框架?
15. Spring 如何处理异常?
以上是一些常见的 Spring 面试题,面试官可能会根据你的回答来深入提问,希望能对你有所帮助。