四、数据库访问与ORM
4.1 JDBC深入
import java.sql.*;
import javax.sql.*;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
/**
* JDBC高级特性
* - 连接池
* - 批处理
* - 事务管理
* - 存储过程调用
*/
public class JDBCAdvanced {
// 使用HikariCP连接池
public static class ConnectionPool {
private static HikariDataSource dataSource;
static {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/test");
config.setUsername("root");
config.setPassword("password");
config.setMaximumPoolSize(10);
config.setMinimumIdle(5);
config.setConnectionTimeout(30000);
config.setIdleTimeout(600000);
config.setMaxLifetime(1800000);
dataSource = new HikariDataSource(config);
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
public static void close() {
if (dataSource != null) {
dataSource.close();
}
}
}
// 批处理示例
public static void batchProcessing() throws SQLException {
String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
try (Connection conn = ConnectionPool.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
// 关闭自动提交
conn.setAutoCommit(false);
for (int i = 0; i < 1000; i++) {
pstmt.setString(1, "User" + i);
pstmt.setInt(2, 20 + (i % 50));
pstmt.addBatch();
// 每100条执行一次
if (i % 100 == 0) {
pstmt.executeBatch();
}
}
pstmt.executeBatch(); // 执行剩余
conn.commit(); // 提交事务
} catch (SQLException e) {
e.printStackTrace();
}
}
// 事务传播与隔离级别
public static void transactionManagement() throws SQLException {
Connection conn = ConnectionPool.getConnection();
try {
// 设置隔离级别
conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
conn.setAutoCommit(false);
// 业务操作1
updateAccount(conn, "A", -100);
// 业务操作2
updateAccount(conn, "B", 100);
conn.commit(); // 提交事务
} catch (SQLException e) {
conn.rollback(); // 回滚事务
throw e;
} finally {
conn.close();
}
}
private static void updateAccount(Connection conn, String account, int amount)
throws SQLException {
String sql = "UPDATE accounts SET balance = balance + ? WHERE account = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, amount);
pstmt.setString(2, account);
pstmt.executeUpdate();
}
}
// 调用存储过程
public static void callStoredProcedure() throws SQLException {
try (Connection conn = ConnectionPool.getConnection();
CallableStatement cstmt = conn.prepareCall("{CALL getUserInfo(?, ?)}")) {
cstmt.setInt(1, 1001); // 输入参数
cstmt.registerOutParameter(2, Types.VARCHAR); // 输出参数
cstmt.execute();
String userName = cstmt.getString(2);
System.out.println("用户名:" + userName);
}
}
// 元数据查询
public static void metadataQuery() throws SQLException {
try (Connection conn = ConnectionPool.getConnection()) {
DatabaseMetaData metaData = conn.getMetaData();
System.out.println("数据库产品:" + metaData.getDatabaseProductName());
System.out.println("数据库版本:" + metaData.getDatabaseProductVersion());
System.out.println("JDBC驱动版本:" + metaData.getDriverVersion());
// 获取所有表
ResultSet tables = metaData.getTables(null, null, "%", new String[]{"TABLE"});
while (tables.next()) {
System.out.println("表名:" + tables.getString("TABLE_NAME"));
}
// 获取主键信息
ResultSet primaryKeys = metaData.getPrimaryKeys(null, null, "users");
while (primaryKeys.next()) {
System.out.println("主键:" + primaryKeys.getString("COLUMN_NAME"));
}
}
}
}
五、Spring框架核心原理
5.1 IoC容器与依赖注入
import org.springframework.beans.factory.annotation.*;
import org.springframework.context.*;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.*;
/**
* Spring IoC核心原理
* - 控制反转:对象的创建和管理交给容器
* - 依赖注入:容器自动注入依赖关系
*/
@Configuration
@ComponentScan
public class SpringCoreDemo {
// 1. Bean定义
@Component
public static class UserService {
@Autowired
private UserRepository userRepository;
public User findUser(Long id) {
return userRepository.findById(id);
}
}
@Repository
public static class UserRepository {
public User findById(Long id) {
return new User(id, "张三");
}
}
// 2. 配置类中的Bean定义
@Configuration
public static class AppConfig {
@Bean
public DataSource dataSource() {
// 配置数据源
return new HikariDataSource();
}
@Bean
@Primary
public UserService userService() {
return new UserService();
}
@Bean
@Scope("prototype") // 原型作用域
public PrototypeBean prototypeBean() {
return new PrototypeBean();
}
}
// 3. 条件化Bean注册
@Configuration
public static class ConditionalConfig {
@Bean
@Conditional(OnWindowsCondition.class)
public WindowsService windowsService() {
return new WindowsService();
}
@Bean
@Conditional(OnMacCondition.class)
public MacService macService() {
return new MacService();
}
}
// 自定义条件
public static class OnWindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return System.getProperty("os.name").toLowerCase().contains("windows");
}
}
public static class OnMacCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return System.getProperty("os.name").toLowerCase().contains("mac");
}
}
// 4. Bean生命周期回调
@Component
public static class LifecycleBean implements InitializingBean, DisposableBean {
@PostConstruct
public void init() {
System.out.println("Bean初始化后执行");
}
@PreDestroy
public void destroy() {
System.out.println("Bean销毁前执行");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("属性设置后执行");
}
@Override
public void destroy() throws Exception {
System.out.println("销毁");
}
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(SpringCoreDemo.class);
UserService userService = context.getBean(UserService.class);
User user = userService.findUser(1L);
System.out.println("用户:" + user);
context.close();
}
static class User {
private Long id;
private String name;
public User(Long id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "User{id=" + id + ", name='" + name + "'}";
}
}
static class WindowsService {}
static class MacService {}
static class PrototypeBean {}
}
5.2 AOP面向切面编程
import org.aspectj.lang.*;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.context.annotation.*;
/**
* AOP核心概念
* - 切面(Aspect):横切关注点的模块化
* - 连接点(JoinPoint):程序执行过程中的点
* - 通知(Advice):切面在连接点执行的动作
* - 切入点(Pointcut):匹配连接点的表达式
*/
@Configuration
@EnableAspectJAutoProxy
@ComponentScan
public class AOPDemo {
// 业务服务
@Service
public static class OrderService {
public void createOrder(String orderId, double amount) {
System.out.println("创建订单:" + orderId + ",金额:" + amount);
if (amount <= 0) {
throw new IllegalArgumentException("订单金额必须大于0");
}
}
public String getOrderStatus(String orderId) {
System.out.println("查询订单状态:" + orderId);
return "PAID";
}
}
// 日志切面
@Aspect
@Component
public static class LoggingAspect {
// 定义切入点
@Pointcut("execution(* com.example.OrderService.*(..))")
public void serviceMethods() {}
// 前置通知
@Before("serviceMethods()")
public void logBefore(JoinPoint joinPoint) {
System.out.println("【前置通知】开始执行:" + joinPoint.getSignature().getName());
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
System.out.println(" 参数" + (i + 1) + ":" + args[i]);
}
}
// 后置通知(无论是否异常)
@After("serviceMethods()")
public void logAfter(JoinPoint joinPoint) {
System.out.println("【后置通知】执行完成:" + joinPoint.getSignature().getName());
}
// 返回通知
@AfterReturning(pointcut = "serviceMethods()", returning = "result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
System.out.println("【返回通知】返回值:" + result);
}
// 异常通知
@AfterThrowing(pointcut = "serviceMethods()", throwing = "ex")
public void logAfterThrowing(JoinPoint joinPoint, Exception ex) {
System.out.println("【异常通知】异常信息:" + ex.getMessage());
}
// 环绕通知(最强大)
@Around("serviceMethods()")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
System.out.println("【环绕通知】开始执行:" + joinPoint.getSignature().getName());
try {
Object result = joinPoint.proceed(); // 执行目标方法
long elapsed = System.currentTimeMillis() - start;
System.out.println("【环绕通知】执行耗时:" + elapsed + "ms");
return result;
} catch (Exception e) {
System.out.println("【环绕通知】执行异常:" + e.getMessage());
throw e;
} finally {
System.out.println("【环绕通知】执行结束");
}
}
}
// 性能监控切面
@Aspect
@Component
public static class PerformanceAspect {
@Around("@annotation(com.example.Monitor)")
public Object monitor(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
long elapsed = System.currentTimeMillis() - start;
System.out.println("性能监控 - " + joinPoint.getSignature().getName() +
" 耗时: " + elapsed + "ms");
return result;
}
}
// 自定义注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Monitor {}
@Service
public static class MonitoredService {
@Monitor
public void criticalOperation() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("关键操作执行");
}
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AOPDemo.class);
OrderService orderService = context.getBean(OrderService.class);
try {
orderService.createOrder("ORD-001", 100.0);
orderService.getOrderStatus("ORD-001");
orderService.createOrder("ORD-002", -10.0);
} catch (Exception e) {
System.out.println("捕获异常:" + e.getMessage());
}
MonitoredService monitoredService = context.getBean(MonitoredService.class);
monitoredService.criticalOperation();
context.close();
}
}
六、性能优化与JVM调优
6.1 JVM参数调优
/**
* JVM调优参数
*
* 堆内存设置
* -Xms2g 初始堆大小
* -Xmx2g 最大堆大小
* -Xmn512m 新生代大小
* -XX:NewRatio=2 老年代/新生代比例
* -XX:SurvivorRatio=8 Eden/Survivor比例
*
* GC选择
* -XX:+UseG1GC 使用G1垃圾收集器
* -XX:+UseConcMarkSweepGC 使用CMS收集器
* -XX:+UseParallelGC 使用并行收集器
*
* GC日志
* -XX:+PrintGCDetails 打印GC详细信息
* -XX:+PrintGCDateStamps 打印GC时间戳
* -Xloggc:gc.log 输出GC日志文件
*/
public class JVMTuning {
// 打印JVM参数
public static void printJVMParams() {
Runtime runtime = Runtime.getRuntime();
System.out.println("处理器核心数:" + runtime.availableProcessors());
System.out.println("最大内存:" + runtime.maxMemory() / 1024 / 1024 + "MB");
System.out.println("总内存:" + runtime.totalMemory() / 1024 / 1024 + "MB");
System.out.println("空闲内存:" + runtime.freeMemory() / 1024 / 1024 + "MB");
// 查看JVM参数
System.out.println("Java版本:" + System.getProperty("java.version"));
System.out.println("Java home:" + System.getProperty("java.home"));
}
}
6.2 代码级性能优化
import java.util.*;
import java.util.stream.*;
/**
* 代码级性能优化技巧
*/
public class CodeOptimization {
// 1. 字符串拼接优化
public static void stringConcatenation() {
// 慢:每次循环创建新StringBuilder
String result = "";
for (int i = 0; i < 10000; i++) {
result += i; // 不推荐
}
// 快:使用StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++) {
sb.append(i);
}
String result2 = sb.toString();
}
// 2. 集合初始化容量优化
public static void collectionCapacity() {
// 慢:需要多次扩容
List<String> list1 = new ArrayList<>();
// 快:指定初始容量,避免扩容
List<String> list2 = new ArrayList<>(1000);
// Map同理
Map<String, String> map = new HashMap<>(16);
}
// 3. 避免自动装箱
public static void autoBoxing() {
// 慢:自动装箱
Integer sum = 0;
for (int i = 0; i < 1000000; i++) {
sum += i; // 每次都会创建Integer对象
}
// 快:使用基本类型
int sum2 = 0;
for (int i = 0; i < 1000000; i++) {
sum2 += i;
}
}
// 4. 使用懒加载
public static class LazyLoading {
private volatile HeavyObject heavyObject;
public HeavyObject getHeavyObject() {
// 双重检查锁定
if (heavyObject == null) {
synchronized (this) {
if (heavyObject == null) {
heavyObject = new HeavyObject();
}
}
}
return heavyObject;
}
}
// 5. 使用Stream并行流(注意线程安全)
public static void parallelStream() {
List<Integer> numbers = IntStream.rangeClosed(1, 10000000)
.boxed()
.collect(Collectors.toList());
// 串行流
long start = System.currentTimeMillis();
long sum1 = numbers.stream()
.mapToLong(i -> i * i)
.sum();
long time1 = System.currentTimeMillis() - start;
// 并行流(适合大量数据且无共享状态)
start = System.currentTimeMillis();
long sum2 = numbers.parallelStream()
.mapToLong(i -> i * i)
.sum();
long time2 = System.currentTimeMillis() - start;
System.out.println("串行流耗时:" + time1 + "ms");
System.out.println("并行流耗时:" + time2 + "ms");
}
// 6. 使用位运算优化
public static void bitwiseOptimization() {
// 模运算优化
int n = 100;
// 慢
if (n % 2 == 0) { }
// 快
if ((n & 1) == 0) { }
// 乘以/除以2的幂
int x = 10;
// 慢
int y1 = x * 8;
// 快
int y2 = x << 3;
}
static class HeavyObject {
private byte[] data = new byte[1024 * 1024]; // 1MB
}
}
6.3、知识体系图谱
Java进阶之路是一条持续探索的旅程。从JVM内存模型到垃圾回收机制,从并发编程到网络通信,从框架原理到性能优化,每一步深入都让你对这门语言的理解更加透彻。
来源:
https://app-abdss1rim1oh.appmiaoda.com