我将基于之前总结的面试题,结合最新技术趋势,为每个核心知识点提供实操示例。这些示例采用Spring Boot 3、Java 17等最新技术栈,并包含完整的代码实现和运行步骤。
java
// 项目结构
java-campus-recruitment-practice
├── src/main/java/com/interview/practice
│ ├── Application.java // 应用启动类
│ ├── config
│ │ ├── AsyncConfig.java // 多线程配置
│ │ └── WebMvcConfig.java // Web配置
│ ├── controller
│ │ ├── UserController.java // 用户管理接口
│ │ └── ThreadController.java // 多线程演示接口
│ ├── entity
│ │ ├── User.java // 用户实体类
│ │ └── Result.java // 通用返回结果
│ ├── service
│ │ ├── UserService.java // 用户服务接口
│ │ ├── impl
│ │ │ └── UserServiceImpl.java // 用户服务实现
│ │ └── ThreadService.java // 多线程服务
│ ├── repository
│ │ └── UserRepository.java // 用户数据访问
│ └── util
│ ├── HashUtils.java // 哈希工具类
│ └── ExceptionUtil.java // 异常处理工具
├── src/main/resources
│ ├── application.yml // 应用配置
│ └── db
│ └── migration // 数据库迁移脚本
└── pom.xml // Maven依赖配置
以下是各模块的核心代码实现:
java
// User.java - 演示Java Bean规范和Lombok使用
package com.interview.practice.entity;
import jakarta.persistence.*;
import lombok.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "users")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String email;
@Column(name = "create_time")
private LocalDateTime createTime;
@Column(name = "update_time")
private LocalDateTime updateTime;
// 演示自定义方法
public void encryptPassword() {
this.password = HashUtils.sha256(this.password);
}
}
java
// UserRepository.java - 演示Spring Data JPA和自定义查询
package com.interview.practice.repository;
import com.interview.practice.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
// 演示自定义SQL查询
@Query("SELECT u FROM User u WHERE u.email = :email")
Optional<User> findByEmail(@Param("email") String email);
}
java
// UserServiceImpl.java - 演示事务管理和线程安全
package com.interview.practice.service.impl;
import com.interview.practice.entity.User;
import com.interview.practice.repository.UserRepository;
import com.interview.practice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
@Transactional
public User createUser(User user) {
// 检查用户名是否已存在
if (userRepository.findByUsername(user.getUsername()).isPresent()) {
throw new IllegalArgumentException("用户名已存在");
}
// 加密密码
user.encryptPassword();
user.setCreateTime(LocalDateTime.now());
user.setUpdateTime(LocalDateTime.now());
return userRepository.save(user);
}
@Override
@Async("asyncExecutor") // 使用自定义线程池
public CompletableFuture<User> getUserAsync(Long id) {
// 模拟耗时操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return CompletableFuture.completedFuture(
userRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("用户不存在"))
);
}
}
java
// AsyncConfig.java - 演示线程池配置
package com.interview.practice.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean(name = "asyncExecutor")
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5); // 核心线程数
executor.setMaxPoolSize(10); // 最大线程数
executor.setQueueCapacity(25); // 队列容量
executor.setThreadNamePrefix("async-thread-");
executor.setRejectedExecutionHandler(
new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy()
);
executor.initialize();
return executor;
}
}
java
// ThreadService.java - 演示各种多线程实现方式
package com.interview.practice.service;
import org.springframework.stereotype.Service;
import java.util.concurrent.*;
@Service
public class ThreadService {
// 1. 继承Thread类
public static class MyThread extends Thread {
@Override
public void run() {
System.out.println("继承Thread类: " + Thread.currentThread().getName());
}
}
// 2. 实现Runnable接口
public static class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("实现Runnable接口: " + Thread.currentThread().getName());
}
}
// 3. 实现Callable接口
public static class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(1000);
return "实现Callable接口: " + Thread.currentThread().getName();
}
}
// 演示线程池使用
public void executeWithThreadPool() {
ExecutorService executor = Executors.newFixedThreadPool(3);
// 提交Runnable任务
executor.submit(new MyRunnable());
// 提交Callable任务
Future<String> future = executor.submit(new MyCallable());
try {
System.out.println(future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
}
// 演示CountDownLatch
public void demoCountDownLatch() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
final int index = i;
new Thread(() -> {
System.out.println("线程" + index + "开始工作");
try {
Thread.sleep(1000 + index * 500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程" + index + "完成工作");
latch.countDown();
}).start();
}
System.out.println("主线程等待所有子线程完成...");
latch.await();
System.out.println("所有子线程完成工作,主线程继续执行");
}
}
java
// UserController.java - 演示RESTful API设计和异常处理
package com.interview.practice.controller;
import com.interview.practice.entity.Result;
import com.interview.practice.entity.User;
import com.interview.practice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.CompletableFuture;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public Result<User> createUser(@RequestBody User user) {
User createdUser = userService.createUser(user);
return Result.success(createdUser);
}
@GetMapping("/{id}")
public Result<User> getUser(@PathVariable Long id) {
User user = userService.getUserAsync(id).join();
return Result.success(user);
}
}
java
// Result.java - 演示通用返回结果封装
package com.interview.practice.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> {
private int code;
private String message;
private T data;
public static <T> Result<T> success(T data) {
return new Result<>(200, "操作成功", data);
}
public static <T> Result<T> error(int code, String message) {
return new Result<>(code, message, null);
}
}
yaml
# application.yml - 应用配置示例
spring:
application:
name: java-interview-practice
datasource:
url: jdbc:mysql://localhost:3306/interview_db?useSSL=false&serverTimezone=UTC
username: root
password: yourpassword
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: validate
show-sql: true
properties:
hibernate:
format_sql: true
flyway:
enabled: true
baseline-on-migrate: true
server:
port: 8080
servlet:
context-path: /api
# 线程池配置
async:
executor:
core-pool-size: 5
max-pool-size: 10
queue-capacity: 25
sql
-- V1__create_user_table.sql - 数据库迁移脚本
CREATE TABLE users (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(100) NOT NULL,
email VARCHAR(50) NOT NULL,
create_time TIMESTAMP NOT NULL,
update_time TIMESTAMP NOT NULL
);
java
// Application.java - 应用启动类
package com.interview.practice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
项目运行步骤:
-
环境准备:
- JDK 17+
- Maven 3.8+
- MySQL 8.0+
-
数据库配置:
- 创建数据库:
CREATE DATABASE interview_db;
- 修改
application.yml
中的数据库连接信息
- 创建数据库:
-
项目构建与运行:
bashgit clone https://github.com/your-repo/java-campus-recruitment-practice.git cd java-campus-recruitment-practice mvn clean install mvn spring-boot:run
-
API测试:
-
创建用户:
bashcurl -X POST http://localhost:8080/api/users \ -H "Content-Type: application/json" \ -d '{"username":"testuser","password":"123456","email":"[email protected]"}'
-
获取用户:
bashcurl http://localhost:8080/api/users/1
-
这个项目涵盖了Java基础、多线程、集合框架、数据库操作和Spring框架等核心知识点的实操示例。你可以根据需要扩展功能,或者针对特定知识点进行深入学习。
互联网公司,校招,Java 面试题,面试题总结,面试答案,实操示例,示例详解,Java 开发,校招面试,Java 面试技巧,编程面试,IT 校招,Java 岗位,面试备考,技术面试
资源地址: pan.quark.cn/s/14fcf913b...