对于Spring需要配置SpringConfig,需要配置的内容如下:
对于Mybatis需要配置MybatisConfig、JdbConfig以及引入Jdbc.properties数据库配置文件。
1.JdbcConfig:
public DataSource dataSouce(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
public PlateformTransactionManager plateformtransactionManager(DataSource dataSource){
DataSourceTransactionManager ds=new DataSourceTransactionManager();
ds.setDataSource(datasource);
return ds;
}
2.MybatisConfig
@Bean
public SqlSessionFactoryBean sqlsessionFactoryBean(DataSource dataSource){
SqlsessionFactoryBean factory = new SqlsessionFactoryBean();
factory.setDataSource(datasource);
return factory;
}
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("Hayaizo.dao");
return msc;
}
SpringMVC需要配置SpringMVCConfig、ServletConfig
1.SpringMVCConfig
2.ServletConfig
AbstractAnnotationConfigDispatcherServletInitilizer
并实现方法package Hayaizo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
@Configuration
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
//拦截请求
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
//配置过滤器,处理中文乱码问题
protected Filter[] getServletFilters(){
CharacterEncodingFilter filter=new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
return new Filter[]{filter};
}
}
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@PostMapping
public Result save(@RequestBody Book book) {
boolean flag=bookService.save(book);
return new Result(flag?Code.SAVE_OK:Code.SAVE_ERR,flag);
}
@PutMapping
public Result update(@RequestBody Book book) {
boolean flag=bookService.update(book);
return new Result(flag?Code.UPDATE_OK:Code.UPDATE_ERR,flag);
}
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id) {
boolean flag=bookService.delete(id);
return new Result(flag?Code.DELETE_OK:Code.DELETE_ERR,flag);
}
@GetMapping("/{id}")
public Result getById(@PathVariable Integer id){
Book book=bookService.selectById(id);
Integer code=book!=null?Code.GET_OK:Code.GET_ERR;
String msg=book!=null? "":"数据查询失败";
return new Result(code,book,msg);
}
@GetMapping
public Result selectAll() {
List<Book> book=bookService.selectAll();
Integer code=book!=null?Code.GET_OK:Code.GET_ERR;
String msg=book!=null? "":"数据查询失败";
return new Result(code,book,msg);
}
}
常用的注解:@RestControllerAdvice、@ExceptionHandler
@RestControllerAdvice:用于标识当前类为REST风格对应的异常处理器
@ExceptionHandler:标识用于处理哪种异常
@RestControllerAdvice
public class ProjectExceptionAdvice {
//@ExceptionHandler用于设置当前处理器类对应的异常类型
@ExceptionHandler(SystemException.class)
public Result doSystemException(SystemException ex){
//记录日志
//发送消息给运维
//发送邮件给开发人员,ex对象发送给开发人员
return new Result(ex.getCode(),null,ex.getMessage());
}
@ExceptionHandler(BusinessException.class)
public Result doBusinessException(BusinessException ex){
return new Result(ex.getCode(),null,ex.getMessage());
}
//除了自定义的异常处理器,保留对Exception类型的异常处理,用于处理非预期的异常
@ExceptionHandler(Exception.class)
public Result doOtherException(Exception ex){
//记录日志
//发送消息给运维
//发送邮件给开发人员,ex对象发送给开发人员
return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请稍后再试!");
}
}
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport{
private ProjectInterceptor interceptor;
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
}
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interceptor).addPathPatterns("/books","/books/*");
}
}
@Component
public class ProjectInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport{
private ProjectInterceptor interceptor;
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
}
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interceptor).addPathPatterns("/books","/books/*");
}
}