随着Java生态的持续发展,2025年的Java学习既需要夯实基础,也需要紧跟技术前沿。本文基于最新技术栈,提供一套包含实操内容的学习路线,帮助你快速掌握企业级Java开发技能。
JDK 21引入了多个实用特性,以下是必须掌握的几个:
// 传统字符串拼接
String sql = "SELECT id, name FROM users WHERE age > " + age + " AND status = '" + status + "'";
// 字符串模板(更简洁、安全)
String sql = STR."SELECT id, name FROM users WHERE age > \{age} AND status = \{status}";
说明:字符串模板避免了传统拼接的繁琐,同时自动处理特殊字符,减少SQL注入风险。
// 定义密封类,只允许指定子类继承
public sealed class Shape permits Circle, Rectangle, Triangle {
public abstract double area();
}
// 子类必须声明为final或sealed
public final class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
说明:密封类增强了代码的可维护性,明确指定了类的继承关系。
// 商品接口
public interface Product {
String getId();
String getName();
double getPrice();
void setPrice(double price);
}
// 具体商品类
public final class PhysicalProduct implements Product {
private final String id;
private final String name;
private double price;
private double weight; // 物理商品特有属性
// 构造方法使用Records特性简化
public PhysicalProduct(String id, String name, double price, double weight) {
this.id = id;
this.name = name;
this.price = price;
this.weight = weight;
}
// 实现接口方法...
}
// 商品管理类(演示封装)
public class ProductManager {
private final Map<String, Product> products = new HashMap<>();
public void addProduct(Product product) {
products.put(product.getId(), product);
}
public Optional<Product> getProduct(String id) {
return Optional.ofNullable(products.get(id));
}
// 批量更新价格(演示Stream API)
public void increasePricesByPercentage(double percentage) {
products.values().forEach(product -> {
double newPrice = product.getPrice() * (1 + percentage / 100);
product.setPrice(newPrice);
});
}
}
JDK 21对Stream API进行了增强,新增了toList()、toMap()等便捷方法:
// 示例:处理订单数据
public class OrderProcessor {
public List<String> getHighValueOrderIds(List<Order> orders, double minAmount) {
// 筛选金额大于minAmount的订单,并提取ID
return orders.stream()
.filter(order -> order.getAmount() > minAmount)
.sorted(Comparator.comparing(Order::getCreateTime).reversed())
.map(Order::getId)
.toList(); // JDK 16+新增,直接返回不可变List
}
// 按状态分组统计订单数量
public Map<OrderStatus, Long> countOrdersByStatus(List<Order> orders) {
return orders.stream()
.collect(Collectors.groupingBy(
Order::getStatus,
Collectors.counting()
));
}
}
JDK 21中虚拟线程已正式转正,极大提高了并发处理能力:
public class VirtualThreadDemo {
public static void main(String[] args) throws InterruptedException {
// 创建虚拟线程执行器
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
// 提交1000个任务
for (int i = 0; i < 1000; i++) {
int taskId = i;
executor.submit(() -> {
processTask(taskId);
return null;
});
}
} // 自动关闭执行器
}
private static void processTask(int taskId) {
System.out.printf("Processing task %d on thread %s%n",
taskId, Thread.currentThread().getName());
// 模拟IO操作
try {
Thread.sleep(Duration.ofMillis(100));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
说明:虚拟线程相比传统线程(平台线程)创建成本极低,适合处理大量IO密集型任务,如Web请求、数据库操作等。
Spring Boot 3.x基于Spring Framework 6.x,最低要求JDK 17,推荐使用JDK 21。
使用Spring Initializr(https://start.spring.io/)创建项目,选择:
// 实体类
@Entity
@Table(name = "books")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
private LocalDate publishDate;
// 构造方法、getter和setter省略
}
// Repository接口
public interface BookRepository extends JpaRepository<Book, Long> {
// 自定义查询
List<Book> findByAuthorContainingIgnoreCase(String author);
// 使用JPQL查询
@Query("SELECT b FROM Book b WHERE b.publishDate > :date")
List<Book> findBooksPublishedAfter(@Param("date") LocalDate date);
}
// 控制器
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookRepository bookRepository;
// 构造函数注入
public BookController(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
@GetMapping
public List<Book> getAllBooks() {
return bookRepository.findAll();
}
@GetMapping("/{id}")
public ResponseEntity<Book> getBookById(@PathVariable Long id) {
return bookRepository.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<Book> createBook(@RequestBody @Valid Book book) {
Book savedBook = bookRepository.save(book);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedBook.getId())
.toUri();
return ResponseEntity.created(location).body(savedBook);
}
// PUT和DELETE方法省略
}
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable()) // 开发环境禁用CSRF
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults())
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);
return http.build();
}
// 内存用户存储(仅用于演示)
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withUsername("user")
.password(passwordEncoder().encode("password"))
.roles("USER")
.build();
UserDetails admin = User.withUsername("admin")
.password(passwordEncoder().encode("admin"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
在application.properties中配置:
# 数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/bookstore?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=password
# JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
添加Redis依赖后,配置缓存:
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10)) // 默认缓存时间10分钟
.serializeKeysWith(RedisSerializationContext.SerializationPair
.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer()));
// 针对不同缓存设置不同过期时间
Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
cacheConfigurations.put("books", config.entryTtl(Duration.ofHours(1)));
cacheConfigurations.put("authors", config.entryTtl(Duration.ofHours(2)));
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.withInitialCacheConfigurations(cacheConfigurations)
.build();
}
}
在服务层使用缓存:
@Service
public class BookService {
private final BookRepository bookRepository;
// 构造函数注入省略
@Cacheable(value = "books", key = "#id")
public Book getBookById(Long id) {
// 缓存未命中时执行
return bookRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Book not found"));
}
@CacheEvict(value = "books", key = "#book.id")
public Book updateBook(Book book) {
return bookRepository.save(book);
}
@CacheEvict(value = "books", allEntries = true)
@Scheduled(fixedRate = 3600000) // 每小时清空一次缓存
public void clearCache() {
// 方法体可以为空,注解完成缓存清除
}
}
使用Spring Cloud 2023.x版本构建微服务系统:
@Service
public class PaymentService {
private final PaymentGatewayClient paymentClient;
// 构造函数注入省略
@CircuitBreaker(name = "paymentService", fallbackMethod = "processPaymentFallback")
@Retry(name = "paymentService")
@RateLimiter(name = "paymentService")
public PaymentResponse processPayment(PaymentRequest request) {
return paymentClient.processPayment(request);
}
// 熔断降级方法
public PaymentResponse processPaymentFallback(PaymentRequest request, Exception e) {
log.error("Payment processing failed", e);
return new PaymentResponse(
UUID.randomUUID().toString(),
request.getAmount(),
PaymentStatus.PENDING,
"Payment is being processed offline"
);
}
}
在application.yml中配置:
resilience4j:
circuitbreaker:
instances:
paymentService:
slidingWindowSize: 10
failureRateThreshold: 50
waitDurationInOpenState: 10000
permittedNumberOfCallsInHalfOpenState: 3
retry:
instances:
paymentService:
maxRetryAttempts: 3
waitDuration: 1000
enableExponentialBackoff: true
exponentialBackoffMultiplier: 2
ratelimiter:
instances:
paymentService:
limitRefreshPeriod: 1s
limitForPeriod: 10
使用Docker和Kubernetes部署Java应用:
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY target/*.jar app.jar
# JVM优化参数
ENTRYPOINT ["java", "-XX:+UseZGC", "-XX:+UseContainerSupport", "-jar", "app.jar"]
# 构建镜像
docker build -t my-java-app:1.0 .
# 运行容器
docker run -d -p 8080:8080 --name my-app my-java-app:1.0
apiVersion: apps/v1
kind: Deployment
metadata:
name: java-app-deployment
spec:
replicas: 3
selector:
matchLabels:
app: java-app
template:
metadata:
labels:
app: java-app
spec:
containers:
- name: java-app
image: my-java-app:1.0
ports:
- containerPort: 8080
resources:
requests:
memory: "512Mi"
cpu: "500m"
limits:
memory: "1Gi"
cpu: "1000m"
readinessProbe:
httpGet:
path: /actuator/health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
通过以上学习路线和实操内容,你将能够掌握2025年企业级Java开发所需的核心技能。建议每个阶段都结合实际项目进行练习,通过解决真实问题来加深理解和提升技能。
2025 Java 最新学习路线,Java 实操指南完整版,Java 零基础入门学习路线,Java 实战应用学习指南,2025 Java 学习路线,Java 最新实操指南,2025 Java 零基础学习2025 Java 零基础学习,Java 从入门到实战路线,Java2025 学习指南,Java 零基础实战应用路线,2025 Java 完整版学习路线,Java 最新实战应用指南,2025 Java 实操学习路线,Java 零基础入门实操指南,2025 Java 学习路线及实操指南
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。