本文目录导读:

我来详细说明Java封装的实际落地案例,从基础到实战:
基础封装案例:用户管理系统
实体类封装 - 用户类
public class User {
// 私有属性 - 封装数据
private Long id;
private String username;
private String password;
private String email;
private Integer age;
private Boolean active;
// 构造方法
public User() {}
public User(String username, String email) {
this.username = username;
this.email = email;
}
// Getter/Setter - 封装访问方法
public Long getId() {
return id;
}
public void setId(Long id) {
if (id == null || id <= 0) {
throw new IllegalArgumentException("ID必须为正数");
}
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
// 业务逻辑验证
if (username == null || username.trim().isEmpty()) {
throw new IllegalArgumentException("用户名不能为空");
}
if (username.length() < 3 || username.length() > 20) {
throw new IllegalArgumentException("用户名长度必须在3-20之间");
}
this.username = username.trim();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
// 邮箱格式验证
if (email != null && !email.matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
throw new IllegalArgumentException("邮箱格式不正确");
}
this.email = email;
}
// 业务方法
public boolean isAdult() {
return age != null && age >= 18;
}
// toString方法
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", email='" + email + '\'' +
'}';
}
}
业务逻辑封装 - 用户服务
public class UserService {
// 封装数据存储
private Map<Long, User> userDatabase = new HashMap<>();
private AtomicLong idGenerator = new AtomicLong(1);
// 封装业务方法
public User createUser(String username, String email) {
// 验证输入
if (username == null || email == null) {
throw new IllegalArgumentException("用户名和邮箱不能为空");
}
// 检查重复
if (isUsernameExists(username)) {
throw new RuntimeException("用户名已存在");
}
// 创建用户
User user = new User(username, email);
user.setId(idGenerator.getAndIncrement());
user.setActive(true);
// 存储用户
userDatabase.put(user.getId(), user);
return user;
}
public User getUserById(Long id) {
if (id == null) {
throw new IllegalArgumentException("ID不能为空");
}
User user = userDatabase.get(id);
if (user == null) {
throw new RuntimeException("用户不存在");
}
return user;
}
public User updateUser(Long id, String email) {
User user = getUserById(id);
user.setEmail(email); // 内部验证
return user;
}
public boolean deleteUser(Long id) {
return userDatabase.remove(id) != null;
}
private boolean isUsernameExists(String username) {
return userDatabase.values().stream()
.anyMatch(u -> u.getUsername().equals(username));
}
}
实际项目封装案例
数据库操作封装 - Repository模式
// 数据库连接封装
public class DatabaseConfig {
private static final String URL = "jdbc:mysql://localhost:3306/mydb";
private static final String USERNAME = "root";
private static final String PASSWORD = "password";
private static Connection connection;
// 单例模式封装数据库连接
private DatabaseConfig() {}
public static Connection getConnection() throws SQLException {
if (connection == null || connection.isClosed()) {
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
return connection;
}
}
// 用户数据访问层封装
public class UserRepository {
private final DatabaseConfig dbConfig;
public UserRepository() {
this.dbConfig = new DatabaseConfig();
}
// 封装CRUD操作
public User save(User user) {
String sql = "INSERT INTO users (username, email, age) VALUES (?, ?, ?)";
try (Connection conn = DatabaseConfig.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
stmt.setString(1, user.getUsername());
stmt.setString(2, user.getEmail());
stmt.setInt(3, user.getAge());
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
user.setId(rs.getLong(1));
}
} catch (SQLException e) {
throw new RuntimeException("保存用户失败", e);
}
return user;
}
public Optional<User> findById(Long id) {
String sql = "SELECT * FROM users WHERE id = ?";
try (Connection conn = DatabaseConfig.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setLong(1, id);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return Optional.of(mapToUser(rs));
}
} catch (SQLException e) {
throw new RuntimeException("查询用户失败", e);
}
return Optional.empty();
}
private User mapToUser(ResultSet rs) throws SQLException {
User user = new User();
user.setId(rs.getLong("id"));
user.setUsername(rs.getString("username"));
user.setEmail(rs.getString("email"));
user.setAge(rs.getInt("age"));
return user;
}
}
配置管理封装
// 配置文件读取封装
public class ApplicationConfig {
private static final String CONFIG_FILE = "application.properties";
private static Properties properties;
static {
properties = new Properties();
try (InputStream input = ApplicationConfig.class.getClassLoader()
.getResourceAsStream(CONFIG_FILE)) {
if (input == null) {
throw new RuntimeException("配置文件不存在: " + CONFIG_FILE);
}
properties.load(input);
} catch (IOException e) {
throw new RuntimeException("加载配置文件失败", e);
}
}
private ApplicationConfig() {}
public static String getProperty(String key) {
return properties.getProperty(key);
}
public static String getProperty(String key, String defaultValue) {
return properties.getProperty(key, defaultValue);
}
public static int getIntProperty(String key) {
return Integer.parseInt(getProperty(key));
}
public static boolean getBooleanProperty(String key) {
return Boolean.parseBoolean(getProperty(key));
}
}
微服务架构封装案例
DTO封装 - 数据传输对象
// 用户注册请求DTO
public class UserRegistrationRequest {
@NotBlank(message = "用户名不能为空")
private String username;
@Email(message = "邮箱格式不正确")
private String email;
@Size(min = 6, max = 20, message = "密码长度必须在6-20之间")
private String password;
// Getter和Setter
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
// 密码不暴露getter,只提供验证方法
public boolean validatePassword(String password) {
return this.password.equals(password);
}
}
// 用户响应DTO
public class UserResponse {
private Long id;
private String username;
private String email;
private LocalDateTime createTime;
// 将实体转换为DTO
public static UserResponse fromUser(User user) {
UserResponse response = new UserResponse();
response.setId(user.getId());
response.setUsername(user.getUsername());
response.setEmail(user.getEmail());
response.setCreateTime(LocalDateTime.now());
return response;
}
// Getter方法
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
private void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
private void setEmail(String email) {
this.email = email;
}
}
工具类封装
// 加密工具类封装
public final class PasswordEncoder {
private static final int STRENGTH = 12;
private PasswordEncoder() {
throw new AssertionError("工具类不允许实例化");
}
// 加密密码
public static String encode(String rawPassword) {
return BCrypt.hashpw(rawPassword, BCrypt.gensalt(STRENGTH));
}
// 验证密码
public static boolean matches(String rawPassword, String encodedPassword) {
return BCrypt.checkpw(rawPassword, encodedPassword);
}
}
// 日期工具类
public final class DateUtils {
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
private DateUtils() {}
public static String formatDate(LocalDate date) {
return date.format(DateTimeFormatter.ofPattern(DATE_FORMAT));
}
public static String formatDateTime(LocalDateTime dateTime) {
return dateTime.format(DateTimeFormatter.ofPattern(DATETIME_FORMAT));
}
public static LocalDate parseDate(String dateStr) {
return LocalDate.parse(dateStr, DateTimeFormatter.ofPattern(DATE_FORMAT));
}
}
实战封装原则和建议
封装层次结构
// 三层架构封装
// Controller层 - 接收请求
@RestController
public class UserController {
private final UserService userService;
@PostMapping("/users")
public ResponseEntity<UserResponse> createUser(@RequestBody UserRegistrationRequest request) {
UserResponse response = userService.createUser(request);
return ResponseEntity.ok(response);
}
}
// Service层 - 业务逻辑
@Service
public class UserService {
private final UserRepository userRepository;
public UserResponse createUser(UserRegistrationRequest request) {
// 业务逻辑
User user = new User();
user.setUsername(request.getUsername());
user.setEmail(request.getEmail());
user.setPassword(PasswordEncoder.encode(request.getPassword()));
user = userRepository.save(user);
return UserResponse.fromUser(user);
}
}
// Repository层 - 数据访问
@Repository
public class UserRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
public User save(User user) {
// 数据库操作
return user;
}
}
封装最佳实践
// 1. 最小权限原则
public class OrderService {
private static final Logger logger = LoggerFactory.getLogger(OrderService.class);
// private方法 - 只对外暴露必要的接口
public Order createOrder(OrderRequest request) {
validateRequest(request);
Order order = buildOrder(request);
processPayment(order);
return order;
}
private void validateRequest(OrderRequest request) {
// 验证逻辑
}
private Order buildOrder(OrderRequest request) {
// 构建订单
return new Order();
}
private void processPayment(Order order) {
// 支付处理
}
}
// 2. 不可变对象
public final class ImmutableUser {
private final Long id;
private final String username;
private final String email;
public ImmutableUser(Long id, String username, String email) {
this.id = id;
this.username = username;
this.email = email;
}
// 只有getter,没有setter
public Long getId() { return id; }
public String getUsername() { return username; }
public String getEmail() { return email; }
}
测试封装
public class UserServiceTest {
private UserService userService;
@Before
public void setUp() {
userService = new UserService();
}
@Test
public void testCreateUser_Success() {
User user = userService.createUser("testuser", "test@example.com");
assertNotNull(user.getId());
assertEquals("testuser", user.getUsername());
}
@Test(expected = IllegalArgumentException.class)
public void testCreateUser_InvalidUsername() {
userService.createUser("ab", "test@example.com");
}
@Test(expected = RuntimeException.class)
public void testCreateUser_DuplicateUsername() {
userService.createUser("testuser", "test@example.com");
userService.createUser("testuser", "other@example.com");
}
}
封装的核心原则:
- 数据和实现细节隐藏
- 只暴露必要的接口
- 内部验证逻辑
- 最小权限原则
- 接口一致性
通过实际项目中的多处封装:
- 实体类封装数据校验
- Service层封装业务逻辑
- Repository封装数据访问
- DTO封装数据传输
- 工具类封装通用功能
- 配置类封装系统配置
这样才能真正做到降低耦合,提高代码的可维护性和可扩展性。