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;
@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 ds = new DataSourceTransactionManager();
ds.setDataSource(dataSource);
return ds;
}
}
MyBatisConfig.java
public class MyBatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean (DataSource dataSource) {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setTypeAliasesPackage("com.it.domain");
return factoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.it.dao");
return msc;
}
}
ServletConfig.java
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[]{"/"};
}
}
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 {
@Autowired
private BookService bookService;
@PostMapping
public boolean save(@RequestBody Book book) {
return bookService.save(book);
}
@PutMapping
public 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);
}
@GetMapping
public List<Book> getAll() {
return bookService.getAll();
}
}
3 数据协议
4 异常处理器
【注】各个层级均可能出现异常,所以将异常统一往上抛,抛到表现层进行处理,且对于不同的异常应该进行分类处理。此外,若将异常放在每个方法中单独书写,代码书写量巨大且无意义,所以应当采用AOP思想进行处理。Spring为此提供了异常处理器。
5 项目异常处理
项目异常分类
具体实施步骤
【注】实际开发的时候,我们可以用 AOP 把那些常见的 circle 异常等包装成 system 异常,对于业务型异常有多少写多少
【注】Result 是用来规范我们的返回结果的