欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > 互联网公司校招 Java 面试题总结及答案实操示例大全

互联网公司校招 Java 面试题总结及答案实操示例大全

2025/11/8 6:55:24 来源:https://blog.csdn.net/sss191s/article/details/148424636  浏览:    关键词:互联网公司校招 Java 面试题总结及答案实操示例大全

我将基于之前总结的面试题,结合最新技术趋势,为每个核心知识点提供实操示例。这些示例采用Spring Boot 3、Java 17等最新技术栈,并包含完整的代码实现和运行步骤。

// 项目结构
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依赖配置

以下是各模块的核心代码实现:

// 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);}
}
// 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);
}
// 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 {@Autowiredprivate UserRepository userRepository;@Override@Transactionalpublic 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("用户不存在")));}
}
// 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;}
}
// 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 {@Overridepublic void run() {System.out.println("继承Thread类: " + Thread.currentThread().getName());}}// 2. 实现Runnable接口public static class MyRunnable implements Runnable {@Overridepublic void run() {System.out.println("实现Runnable接口: " + Thread.currentThread().getName());}}// 3. 实现Callable接口public static class MyCallable implements Callable<String> {@Overridepublic 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();}// 演示CountDownLatchpublic 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("所有子线程完成工作,主线程继续执行");}
}
// 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 {@Autowiredprivate UserService userService;@PostMappingpublic 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);}
}
// 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);}
}
# application.yml - 应用配置示例
spring:application:name: java-interview-practicedatasource:url: jdbc:mysql://localhost:3306/interview_db?useSSL=false&serverTimezone=UTCusername: rootpassword: yourpassworddriver-class-name: com.mysql.cj.jdbc.Driverjpa:hibernate:ddl-auto: validateshow-sql: trueproperties:hibernate:format_sql: trueflyway:enabled: truebaseline-on-migrate: trueserver:port: 8080servlet:context-path: /api# 线程池配置
async:executor:core-pool-size: 5max-pool-size: 10queue-capacity: 25
-- 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
);
// 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);}
}

项目运行步骤:

  1. 环境准备

    • JDK 17+
    • Maven 3.8+
    • MySQL 8.0+
  2. 数据库配置

    • 创建数据库:CREATE DATABASE interview_db;
    • 修改application.yml中的数据库连接信息
  3. 项目构建与运行

    git clone https://github.com/your-repo/java-campus-recruitment-practice.git
    cd java-campus-recruitment-practice
    mvn clean install
    mvn spring-boot:run
    
  4. API测试

    • 创建用户:
      curl -X POST http://localhost:8080/api/users \
      -H "Content-Type: application/json" \
      -d '{"username":"testuser","password":"123456","email":"test@example.com"}'
      
    • 获取用户:
      curl http://localhost:8080/api/users/1
      

这个项目涵盖了Java基础、多线程、集合框架、数据库操作和Spring框架等核心知识点的实操示例。你可以根据需要扩展功能,或者针对特定知识点进行深入学习。


代码获取方式

(夸克网盘)点击查看


关注我获取更多内容

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词