以下是按照您的要求,结合最新Java技术(如Java 8+特性、Spring Boot、单元测试等)生成的实操内容。文章将包含技术说明和代码实现,帮助学生掌握现代Java开发技能。
本项目使用Spring Boot 3.0和Java 17开发一个简单的在线图书管理系统,包含图书CRUD操作、用户认证和单元测试。通过这个项目,你将掌握:
使用Spring Initializr快速搭建项目,添加以下依赖:
// pom.xml(关键依赖)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
# 数据库配置
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.h2.console.enabled=true
# JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
使用Lombok注解简化代码,定义Book
实体:
// Book.java
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "书名不能为空")
private String title;
@NotBlank(message = "作者不能为空")
private String author;
@Min(value = 0, message = "价格不能为负数")
private Double price;
private LocalDateTime createTime;
@PrePersist
public void prePersist() {
this.createTime = LocalDateTime.now();
}
}
使用Spring Data JPA的JpaRepository
实现CRUD操作:
// BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {
// 自定义查询方法
List<Book> findByAuthor(String author);
// 使用Java Stream API处理大结果集
@Query("SELECT b FROM Book b")
Stream<Book> streamAllBooks();
}
使用@Service
注解创建业务逻辑层:
// BookService.java
public interface BookService {
Book saveBook(Book book);
Book getBookById(Long id);
List<Book> getAllBooks();
List<Book> getBooksByAuthor(String author);
void deleteBook(Long id);
}
// BookServiceImpl.java
@Service
@RequiredArgsConstructor
public class BookServiceImpl implements BookService {
private final BookRepository bookRepository;
@Override
public Book saveBook(Book book) {
return bookRepository.save(book);
}
@Override
public Book getBookById(Long id) {
return bookRepository.findById(id)
.orElseThrow(() -> new EntityNotFoundException("Book not found with id: " + id));
}
@Override
public List<Book> getAllBooks() {
// 使用Java Stream API过滤和排序
return bookRepository.findAll().stream()
.sorted(Comparator.comparing(Book::getCreateTime).reversed())
.collect(Collectors.toList());
}
@Override
public List<Book> getBooksByAuthor(String author) {
return bookRepository.findByAuthor(author);
}
@Override
public void deleteBook(Long id) {
bookRepository.deleteById(id);
}
}
使用@RestController
和@RequestMapping
注解创建API接口:
// BookController.java
@RestController
@RequestMapping("/api/books")
@RequiredArgsConstructor
public class BookController {
private final BookService bookService;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Book createBook(@Valid @RequestBody Book book) {
return bookService.saveBook(book);
}
@GetMapping("/{id}")
public Book getBook(@PathVariable Long id) {
return bookService.getBookById(id);
}
@GetMapping
public List<Book> getAllBooks() {
return bookService.getAllBooks();
}
@GetMapping("/author/{author}")
public List<Book> getBooksByAuthor(@PathVariable String author) {
return bookService.getBooksByAuthor(author);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteBook(@PathVariable Long id) {
bookService.deleteBook(id);
}
}
使用@Configuration
和@EnableWebSecurity
注解配置基本认证:
// SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/books").permitAll() // 公开访问的API
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.csrf().disable();
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.builder()
.username("admin")
.password("{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76PK") // 密码: password
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user);
}
}
使用JUnit 5和Mockito测试服务层逻辑:
// BookServiceImplTest.java
@ExtendWith(MockitoExtension.class)
class BookServiceImplTest {
@Mock
private BookRepository bookRepository;
@InjectMocks
private BookServiceImpl bookService;
@Test
void whenSaveBook_thenReturnBook() {
// 准备测试数据
Book book = Book.builder()
.title("Java实战")
.author("John Doe")
.price(99.9)
.build();
// 模拟Repository行为
Mockito.when(bookRepository.save(any(Book.class))).thenReturn(book);
// 执行测试
Book savedBook = bookService.saveBook(book);
// 验证结果
assertNotNull(savedBook);
assertEquals("Java实战", savedBook.getTitle());
Mockito.verify(bookRepository, times(1)).save(any(Book.class));
}
}
使用Spring MVC Test测试API接口:
// BookControllerTest.java
@WebMvcTest(BookController.class)
class BookControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private BookService bookService;
@Test
void givenBooks_whenGetAllBooks_thenReturnJsonArray() throws Exception {
// 准备测试数据
Book book = Book.builder()
.id(1L)
.title("Java实战")
.author("John Doe")
.price(99.9)
.build();
// 模拟Service行为
Mockito.when(bookService.getAllBooks()).thenReturn(Collections.singletonList(book));
// 执行测试
mockMvc.perform(get("/api/books"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].title", is("Java实战")));
}
}
运行主类BookManagementApplication
,Spring Boot会自动配置并启动应用。访问H2控制台:http://localhost:8080/h2-console
,使用配置的数据库连接信息登录。
使用Postman或curl测试API:
curl -X POST "http://localhost:8080/api/books" \
-H "Content-Type: application/json" \
-d '{"title":"Effective Java","author":"Joshua Bloch","price":89.9}'
curl "http://localhost:8080/api/books"
通过这个项目,你掌握了现代Java开发的核心技术:
这些技术是Java开发的核心技能,也是大学期末考试和企业面试的重点内容。建议你动手实践,尝试扩展这个项目(如添加分页功能、整合Redis缓存等),加深对Java技术栈的理解。
Java 项目,大学期末实操,在线图书管理系统,图书管理系统设计,图书管理系统实现,Java 图书管理系统,完整功能模块,期末 Java 项目,图书管理系统开发,Java 实操项目,大学生 Java 项目,图书管理系统代码,Java 课程设计,图书管理系统案例,Java 期末作业
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。