1 整合配置
1.1 流程
1.2 Spring 整合 MyBatis
1.3 Spring 整合 SpringMVC
1.4 配置代码
JdbcConfig.java
public class JdbcConfig {@Value("${jdbc.driver}")private String driver;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Beanpublic DataSource dataSource() {DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName(driver);dataSource.setUrl(url);dataSource.setUsername(username);dataSource.setPassword(password);return dataSource;}@Beanpublic PlatformTransactionManager transactionManager(DataSource dataSource) {DataSourceTransactionManager ds = new DataSourceTransactionManager();ds.setDataSource(dataSource);return ds;}}
MyBatisConfig.java
public class MyBatisConfig {@Beanpublic SqlSessionFactoryBean sqlSessionFactoryBean (DataSource dataSource) {SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();factoryBean.setDataSource(dataSource);factoryBean.setTypeAliasesPackage("com.it.domain");return factoryBean;}@Beanpublic MapperScannerConfigurer mapperScannerConfigurer() {MapperScannerConfigurer msc = new MapperScannerConfigurer();msc.setBasePackage("com.it.dao");return msc;}
}
ServletConfig.java
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {@Overrideprotected Class<?>[] getRootConfigClasses() {return new Class[]{SpringConfig.class};}@Overrideprotected Class<?>[] getServletConfigClasses() {return new Class[]{SpringMvcConfig.class};}@Overrideprotected String[] getServletMappings() {return new String[]{"/"};}
}
SpringConfig.java
@Configuration
@ComponentScan({"com.it.service"})
@PropertySource("jdbc.properties")
@Import({JdbcConfig.class, MyBatisConfig.class})
@EnableTransactionManagement //开启注解事务驱动
public class SpringConfig {
}
SpringMvcConfig.java
@Configuration
@ComponentScan("com.it.controller")
@EnableWebMvc
public class SpringMvcConfig {}
2 功能模块开发
BookController.java
@RestController
@RequestMapping("/books")
public class BookController {@Autowiredprivate BookService bookService;@PostMappingpublic boolean save(@RequestBody Book book) {return bookService.save(book);}@PutMappingpublic boolean update(@RequestBody Book book) {return bookService.update(book);}@DeleteMapping("/{id}")public boolean delete(@PathVariable Integer id) {return bookService.delete(id);}@GetMapping("/{id}")public Book getById(@PathVariable Integer id) {return bookService.getById(id);}@GetMappingpublic List<Book> getAll() {return bookService.getAll();}}
3 数据协议
4 异常处理器
【注】各个层级均可能出现异常,所以将异常统一往上抛,抛到表现层进行处理,且对于不同的异常应该进行分类处理。此外,若将异常放在每个方法中单独书写,代码书写量巨大且无意义,所以应当采用AOP思想进行处理。Spring为此提供了异常处理器。
5 项目异常处理
项目异常分类
具体实施步骤
【注】实际开发的时候,我们可以用 AOP 把那些常见的 circle 异常等包装成 system 异常,对于业务型异常有多少写多少
【注】Result 是用来规范我们的返回结果的