package co.jp.app.service; import jakarta.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import co.jp.app.entity.UserEntity; import co.jp.app.repository.UserRepository; @Service public class UserService { private final UserRepository userEntityRepository; @Autowired public UserService(UserRepository userEntityRepository, PasswordEncoder passwordEncoder ) { this.userEntityRepository = userEntityRepository; this.passwordEncoder = passwordEncoder; } @Transactional // 整个注册过程应该是一个事务 public UserEntity registerNewUser(String name, String email, String rawPassword) throws Exception { // 1. 检查邮箱是否已被注册 if (userEntityRepository.existsByEmail(email)) { throw new Exception("错误:该邮箱地址已被注册!"); // 或者自定义异常 } // (可选) 检查用户名是否已被注册 (如果您有用户名字段) // if (userEntityRepository.existsByUsername(username)) { // throw new Exception("错误:该用户名已被注册!"); // } // 2. 创建新的 UserEntity 对象 UserEntity newUser = new UserEntity(); newUser.setName(name); newUser.setEmail(email); // 3. 对密码进行哈希加密 (非常重要!) // String hashedPassword = passwordEncoder.encode(rawPassword); // newUser.setPassword(hashedPassword); newUser.setPassword(rawPassword); // 实际项目中必须加密!这里为了简化先直接赋值 // 4. 设置其他默认属性,例如账户状态、角色等 (如果需要) // newUser.setActive(true); // newUser.setRoles(...); // 5. 保存新用户到数据库 return userEntityRepository.save(newUser); } }