SSM注解整合和3种异常处理

  • Post author:
  • Post category:其他


包结构示意图

在这里插入图片描述



Jdbc配置类

这里使用了PropertySource注解引入外部文件

properties配置文件在此省略了

@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.password}")
    private String password;
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.username}")
    private String username;

    //设置连接池
    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
    //设置事务管理器 (声明式事务)
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        //DataSourceTransactionManager搭配mybatis
        DataSourceTransactionManager ds = new DataSourceTransactionManager();
        ds.setDataSource(dataSource);
        return ds;
    }
}



Mybatis配置类

public class MybatisConfig {
// 创建sqlsession工厂,并扫描实体类
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.rhl.pojo");
        return factoryBean;

    }

}



servlet配置类

这里集继承AbstractAnnotationConfigDispatcherServletInitializer类,可以快速初始化Servlet3.0环境

public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    protected Class<?>[] getRootConfigClasses() {
        //指定spring配置加载(根配置)
        return new Class[]{SpringConfig.class};
    }

    protected Class<?>[] getServletConfigClasses() {
        //指定springmvc配置加载
        return new Class[]{SpringMvcConfig.class};
    }

    protected String[] getServletMappings() {
        //配置springmvc拦截路径为 / (全路径)
        return new String[]{"/"};
    }
    //中文乱码过滤器
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding("utf-8");
        return new Filter[]{encodingFilter};
    }
}



Spring配置类

@Configuration
@ComponentScan(value = "com.rhl",
        excludeFilters ={@ComponentScan.Filter(
                type = FilterType.ANNOTATION,
                classes = {RestController.class, Controller.class, RestControllerAdvice.class})} )
                //@ComponentScan.Filter注解可以过滤重复扫描的注解,提高效率
//@EnableAspectJAutoProxy//开启AOP注解支持
@Import({JdbcConfig.class,MybatisConfig.class}) //引入外部配置
@EnableTransactionManagement//开启事务管理,底层对事务注解支持
@MapperScan("com/rhl/mapper")
public class SpringConfig {
}

SpringMvc配置类

@ComponentScan({"com.rhl.controller","com.rhl.advice"})//扫描web层资源,并加入IOC容器
//@EnableWebMvc//注解底层以来与DispatcherServlet,而servlet的启动依赖于servlet容器
@EnableWebMvc//开启springMvc扩展功能的支持,包含:json与javabean的转换、日期格式等转换、自定义转换等等
public class SpringMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        //放行静态资源 这里只是举例 
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
        registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
    }

}

异常分为三类,我们首先注册一个异常处理器

@RestControllerAdvice
public class ProjectExceptionAdvice {

    //专门处理BusinessException
    @ExceptionHandler(BusinessException.class)
    public Result doBusinessException(BusinessException ex){
        //发送对应消息传递给用户,提醒规范操作
        return new Result(ex.getCode(),ex.getMessage());
    }

    //专门处理SystemException
    @ExceptionHandler(SystemException.class)
    public Result doSystemException(SystemException ex){
//        发送固定消息传递给用户,安抚用户
//        发送特定消息给运维人员,提醒维护
//                记录日志
        return new Result(ex.getCode(),ex.getMessage());
    }

    //处理其他未知异常
    @ExceptionHandler(Exception.class)
    public Result doException(Exception ex){

        return new Result(Code.SYSTEM_UNKNOW_ERR,"服务器正在维护,请稍后访问");
    }
}
public class BusinessException extends RuntimeException{
    //异常的状态码
    private Integer code;

    public BusinessException(Integer code,String message){
        super(message);
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}

public class SystemException extends RuntimeException{
    //异常的状态码
    private Integer code;

    public SystemException(Integer code, String message){
        super(message);
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}



版权声明:本文为weixin_50965314原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。