6.2.1 被调用服务方法
添加获取图书业务服务代码:
package com.marshal.springcloud.book.service;
import com.marshal.springcloud.book.entity.Book;
import com.marshal.springcloud.book.exception.BookNotFoundException;
import com.marshal.springcloud.book.repository.BookRepository;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
/**
* @Author 王毅
* @Date 2020/8/31 10:07
*/
@Service
public class BookService {
@Resource
private BookRepository bookRepository;
public List<Book> findAll() {
return bookRepository.findAll();
}
public Book getBookById(Long id){
Optional<Book> optional = bookRepository.findById(id);
Book book = null;
if (optional.isPresent()) {
book = optional.get();
} else {
throw new BookNotFoundException("Book " + id + " not found !!");
}
return book;
}
}
编写创建图书未查询到异常:
package com.marshal.springcloud.book.exception;
/**
* @Author 王毅
* @Date 2020/8/31 11:32
*/
public class BookNotFoundException extends RuntimeException {
public BookNotFoundException(String message) {
super(message);
}
}
6.2.2 控制器方法
编写控制器类获取图书信息方法:
package com.marshal.springcloud.book.controller;
import com.marshal.springcloud.book.entity.Book;
import com.marshal.springcloud.book.service.BookService;
import jdk.nashorn.internal.objects.annotations.Getter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author 王毅
* @Date 2020/8/31 10:09
*/
@RestController
public class BookController {
@Resource
private BookService bookService;
@GetMapping("/booklist")
public Map bookList() {
Map result = new HashMap();
try {
List bookList = bookService.findAll();
result.put("code", 0);
result.put("message", "success");
result.put("data", bookList);
} catch (Exception e) {
e.printStackTrace();
result.put("code", e.getClass().getSimpleName());
result.put("message", e.getMessage());
}
return result;
}
@GetMapping("/getBookInfo")
public Map getBookInfo(Long bookId) {
Map result = new HashMap();
try {
Book book = bookService.getBookById(bookId);
result.put("code", 0);
result.put("message", "success");
result.put("data", book);
} catch (Exception e) {
e.printStackTrace();
result.put("code", e.getClass().getSimpleName());
result.put("message", e.getMessage());
}
return result;
}
}
6.2.3 运行测试
代码编写测试: