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 druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(driver);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
return druidDataSource;
}
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
public class MybatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setTypeAliasesPackage("com.pojo");
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.dao");
return mapperScannerConfigurer;
}
}
public class ServletCongif 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[]{"/"};
}
}
@Configuration
@ComponentScan("com.service")
@PropertySource("classpath:jdbc.properties")
//@PropertySource("jdbc.properties")
@Import({JdbcConfig.class, MybatisConfig.class})
@EnableTransactionManagement//事务
public class SpringConfig {
}
@Configuration
@ComponentScan("com.controller")
@EnableWebMvc
public class SpringMvcConfig {
}
1.4开启事务
@Transactional
public interface BookService {
public boolean add(Book book);
public boolean update(Book book);
public boolean delete(Integer id);
public Book getById(Integer id);
public List getAll();
}
2.业务层
2.1 pojo
public class Book {
private Integer id;
private String type;
private String name;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", type='" + type + ''' +
", name='" + name + ''' +
", description='" + description + ''' +
'}';
}
}
2.2 dao
public interface BookDao {
@Insert("insert into tbl_book values(null,#{type},#{name},#{description})")
public int add(Book book);//返回行计数
@Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
public int update(Book book);
@Delete("delete from tbl_book where id = #{id}")
public int delete(Integer id);
@Select("select * from tbl_book where id = #{id}")
public Book getById(Integer id);
@Select("select * from tbl_book")
public List getAll();
}
2.3service
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
@Override
public boolean add(Book book) {
int add = bookDao.add(book);
return add > 0;
}
@Override
public boolean update(Book book) {
int update = bookDao.update(book);
return update > 0;
}
@Override
public boolean delete(Integer id) {
int delete = bookDao.delete(id);
return delete > 0;
}
@Override
public Book getById(Integer id) {
return bookDao.getById(id);
}
@Override
public List getAll() {
return bookDao.getAll();
}
}
2.4业务层测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {
@Autowired
private BookService bookService;
@Test
public void testGetById() {
Book book = bookService.getById(1);
System.out.println(book);
}
@Test
public void testGetAll(){
List all = bookService.getAll();
System.out.println(all);
}
}
3.表现层
3.1数据封装
public class Result {
private Integer code;
private Object data;
private String message;
public Result() {
}
public Result(Integer code, Object data, String massage) {
this.data = data;
this.code = code;
this.message = massage;
}
public Result(Integer code, Object data) {
this.data = data;
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String massage) {
this.message = massage;
}
}
public class Code {
public static final Integer ADD_OK = 20011;
public static final Integer DELETE_0K = 20021;
public static final Integer UPDATE_OK = 20031;
public static final Integer GET_OK = 20041;
public static final Integer ADD_ERR = 20010;
public static final Integer DELETE_ERR = 20020;
public static final Integer UPDATE_ERR = 20030;
public static final Integer GET_ERR = 20048;
}
3.2controller
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@PostMapping
public Result add(@RequestBody Book book) {
boolean flag = bookService.add(book);
return new Result(flag ? Code.ADD_OK : Code.ADD_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_0K : Code.DELETE_ERR, flag);
}
@GetMapping("/{id}")
public Result getById(@PathVariable Integer id) {
Book book = bookService.getById(id);
Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
String massage = book != null ? "" : "数据查询失败,请重试";
return new Result(code, book, massage);
}
@GetMapping
public Result getAll() {
List list = bookService.getAll();
Integer code = list != null ? Code.GET_OK : Code.GET_ERR;
String massage = list != null ? "" : "数据查询失败,请重试";
return new Result(code, list, massage);
}
}
3.3异常处理
public class BusinessException extends RuntimeException {
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
}
public BusinessException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
}
public class SystemException extends RuntimeException {
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public SystemException(Integer code, String message) {
super(message);
this.code = code;
}
public SystemException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
}
@RestControllerAdvice
public class ProjectExceptionAdvice {
//系统异常处理
@ExceptionHandler(SystemException.class)//定义处理哪一种异常
public Result doSystemException(SystemException 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());
}
//其他异常处理
@ExceptionHandler(Exception.class)//定义处理哪一种异常
public Result doException(BusinessException ex) {
//记录日志
//发送消息给运维
//发送邮件给开发人员
return new Result(Code.SYSTEM_UNKNOWN_ERR, null, "系统繁忙,请稍后再试");
}
}
public class Code {
public static final Integer SYSTEM_ERR = 50001;
public static final Integer SYSTEM_TIMEOUT_ERR = 50002;
public static final Integer SYSTEM_UNKNOWN_ERR = 59999;
public static final Integer BUSINESS_ERR = 60002;
}
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
@Override
public boolean add(Book book) {
try {
int add = bookDao.add(book);
return add > 0;
} catch (Exception e) {
throw new SystemException(Code.SYSTEM_TIMEOUT_ERR, "服务器异常", e);
}
}
@Override
public boolean update(Book book) {
try {
int update = bookDao.update(book);
return update > 0;
} catch (Exception e) {
throw new SystemException(Code.SYSTEM_TIMEOUT_ERR, "服务器异常", e);
}
}
@Override
public boolean delete(Integer id) {
if (id <= 0) {
throw new BusinessException(Code.BUSINESS_ERR, "无效的id");
}
try {
int delete = bookDao.delete(id);
return delete > 0;
} catch (Exception e) {
throw new SystemException(Code.SYSTEM_TIMEOUT_ERR, "服务器异常", e);
}
}
@Override
public Book getById(Integer id) {
if (id <= 0) {
throw new BusinessException(Code.BUSINESS_ERR, "无效的id");
}
try {
return bookDao.getById(id);
} catch (Exception e) {
throw new SystemException(Code.SYSTEM_TIMEOUT_ERR, "服务器异常", e);
}
}
@Override
public List getAll() {
try {
return bookDao.getAll();
} catch (Exception e) {
throw new SystemException(Code.SYSTEM_TIMEOUT_ERR, "服务器异常", e);
}
}
}
4.前后台联合
4.1静态资源放行
//静态资源放行
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@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/");
}
}
@Configuration
@ComponentScan({"com.controller","com.config"})
@EnableWebMvc
public class SpringMvcConfig {
}