Java组件使用方法与封装指南
一、核心组件使用方法
1. 跨平台开发
Java通过JVM实现跨平台,以下是跨平台开发的基本步骤:
// 1. 编写Java源代码
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
// 2. 编译Java代码
javac HelloWorld.java
// 3. 在不同平台运行字节码
java HelloWorld
2. 面向对象编程
Java面向对象编程的基本结构:
// 定义父类
public class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating.");
}
public abstract void sound(); // 抽象方法
}
// 定义子类
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
@Override
public void sound() {
System.out.println("Woof!");
}
}
// 使用多态
Animal myDog = new Dog("Buddy");
myDog.eat(); // 输出: Buddy is eating.
myDog.sound(); // 输出: Woof!
3. 多线程编程
Java多线程编程的基本用法:
// 方式1: 继承Thread类
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running: " + Thread.currentThread().getName());
}
}
// 方式2: 实现Runnable接口
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable running: " + Thread.currentThread().getName());
}
}
// 使用线程池
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.submit(new MyRunnable());
}
executor.shutdown();
4. 数据库操作
使用JDBC进行数据库操作的基本流程:
// 加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 建立连接
String url = "jdbc:mysql://localhost:3306/mydb";
String username = "root";
String password = "password";
Connection conn = DriverManager.getConnection(url, username, password);
// 执行查询
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
// 关闭资源
rs.close();
stmt.close();
conn.close();
二、组件封装方法
1. 工具类封装
将常用功能封装为静态工具类:
public class StringUtils {
// 私有构造函数防止实例化
private StringUtils() {}
// 判断字符串是否为空
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
// 字符串反转
public static String reverse(String str) {
if (isEmpty(str)) return str;
return new StringBuilder(str).reverse().toString();
}
}
// 使用示例
boolean empty = StringUtils.isEmpty("test");
String reversed = StringUtils.reverse("hello");
2. 数据库连接池封装
封装HikariCP连接池:
public class DBConnectionPool {
private static HikariConfig config = new HikariConfig();
private static HikariDataSource ds;
static {
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
config.setUsername("root");
config.setPassword("password");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
ds = new HikariDataSource(config);
}
private DBConnectionPool() {}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
// 使用示例
try (Connection conn = DBConnectionPool.getConnection()) {
// 执行数据库操作
} catch (SQLException e) {
e.printStackTrace();
}
3. 自定义异常封装
封装业务异常:
// 基础业务异常类
public class BusinessException extends RuntimeException {
private int errorCode;
public BusinessException(int errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
}
// 用户不存在异常
public class UserNotFoundException extends BusinessException {
public UserNotFoundException(String userId) {
super(404, "User not found: " + userId);
}
}
// 使用示例
public User getUser(String userId) {
User user = userRepository.findById(userId);
if (user == null) {
throw new UserNotFoundException(userId);
}
return user;
}
4. 通用响应结果封装
封装API返回结果:
public class ApiResponse<T> {
private int code;
private String message;
private T data;
private boolean success;
public static <T> ApiResponse<T> success(T data) {
ApiResponse<T> response = new ApiResponse<>();
response.setCode(200);
response.setMessage("Success");
response.setData(data);
response.setSuccess(true);
return response;
}
public static <T> ApiResponse<T> error(int code, String message) {
ApiResponse<T> response = new ApiResponse<>();
response.setCode(code);
response.setMessage(message);
response.setSuccess(false);
return response;
}
// getter和setter方法
}
// 使用示例
@GetMapping("/users/{id}")
public ApiResponse<User> getUser(@PathVariable String id) {
try {
User user = userService.getUser(id);
return ApiResponse.success(user);
} catch (UserNotFoundException e) {
return ApiResponse.error(404, e.getMessage());
}
}
三、封装最佳实践
- 单一职责原则:每个组件只负责一个明确的功能
- 高内聚低耦合:组件内部联系紧密,与外部依赖少
- 可配置化:关键参数通过配置文件或注解注入
- 异常处理:封装内部处理细节异常,对外抛出统一业务异常
- 文档注释:提供清晰的Javadoc注释,说明组件用途和使用方法
遵循这些原则可以创建出高质量、可复用的Java组件,提高开发效率和代码质量。
准备了一些面试资料,请在以下链接中获取
https://pan.quark.cn/s/4459235fee85
关注我获取更多内容