Loading...
Loading...
Comprehensive Java development skill based on Alibaba Java Coding Guidelines (Songshan Edition). Use when writing, reviewing, or refactoring Java code to ensure compliance with industry best practices. Triggers on: (1) Writing new Java code (.java files), (2) Reviewing existing Java code, (3) Refactoring Java projects, (4) Database design with MySQL, (5) API design and implementation, (6) Unit testing, (7) Concurrent programming, (8) Security implementation, or any Java development tasks requiring adherence to coding standards.
npx skill4agent add story-has-you/skills java-devUserServiceOrderControllergetUserByIduserNameMAX_COUNTDEFAULT_SIZEcom.company.moduleAbstract*Base**Exception*Test*Implisget*list*count*save*remove*update*==equals()SELECT *finally@Override// ❌ Wrong: Magic numbers
if (status == 1) { ... }
// ✅ Correct: Named constants
private static final int STATUS_ACTIVE = 1;
if (status == STATUS_ACTIVE) { ... }
// ❌ Wrong: Comparing wrapper types with ==
Integer a = 128;
Integer b = 128;
if (a == b) { ... } // May fail!
// ✅ Correct: Use equals()
if (a.equals(b)) { ... }
// ❌ Wrong: Empty catch block
try {
doSomething();
} catch (Exception e) {
// Silent failure
}
// ✅ Correct: Handle or rethrow
try {
doSomething();
} catch (Exception e) {
logger.error("Failed to do something", e);
throw new BusinessException("Operation failed", e);
}
// ❌ Wrong: Creating threads directly
new Thread(() -> doWork()).start();
// ✅ Correct: Use thread pool
ExecutorService executor = new ThreadPoolExecutor(
corePoolSize, maxPoolSize, keepAliveTime,
TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
new ThreadFactoryBuilder().setNameFormat("worker-%d").build()
);
executor.submit(() -> doWork());user_orderidcreate_timeupdate_timeis_*is_deletedBIGINT UNSIGNEDDECIMALFLOATDOUBLE// ✅ Correct: Parameterized query
String sql = "SELECT id, user_name, email FROM user WHERE id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setLong(1, userId);
// ✅ Correct: MyBatis parameter binding
@Select("SELECT * FROM user WHERE user_name = #{userName}")
User selectByUserName(@Param("userName") String userName);
// ❌ Wrong: String concatenation (SQL injection risk!)
String sql = "SELECT * FROM user WHERE user_name = '" + userName + "'";// ✅ Correct exception handling
public User getUserById(Long userId) {
if (userId == null) {
throw new IllegalArgumentException("userId cannot be null");
}
User user = userDao.selectById(userId);
if (user == null) {
throw new NotFoundException("User not found: " + userId);
}
return user;
}
// ✅ Correct logging with exception
try {
processOrder(order);
} catch (Exception e) {
logger.error("Failed to process order, orderId: {}", order.getId(), e);
throw new BusinessException("订单处理失败", e);
}ThreadPoolExecutorExecutorsvolatileAtomicXxxSimpleDateFormatDateTimeFormatterThreadLocal// ✅ Correct: Thread pool with proper configuration
ThreadPoolExecutor executor = new ThreadPoolExecutor(
10, // corePoolSize
20, // maximumPoolSize
60L, // keepAliveTime
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(100),
new ThreadFactoryBuilder().setNameFormat("order-processor-%d").build(),
new ThreadPoolExecutor.CallerRunsPolicy()
);
// ✅ Correct: ThreadLocal cleanup
private static final ThreadLocal<User> USER_CONTEXT = new ThreadLocal<>();
public void processRequest() {
try {
USER_CONTEXT.set(getCurrentUser());
// Process request
} finally {
USER_CONTEXT.remove(); // Critical: prevent memory leak
}
}// ✅ Correct: Input validation
public void createUser(UserCreateRequest request) {
if (StringUtils.isBlank(request.getUserName())) {
throw new ValidationException("用户名不能为空");
}
if (!ValidationUtils.isValidMobile(request.getMobile())) {
throw new ValidationException("手机号格式不正确");
}
// Process...
}
// ✅ Correct: Sensitive data masking
logger.info("User login, mobile: {}", maskMobile(user.getMobile()));*Testtest*@ExtendWith(MockitoExtension.class)
public class UserServiceTest {
@Mock
private UserDao userDao;
@InjectMocks
private UserService userService;
@Test
@DisplayName("根据ID获取用户 - 正常情况")
public void testGetUserById_Success() {
// Given
Long userId = 1L;
User mockUser = new User();
mockUser.setId(userId);
mockUser.setUserName("test");
when(userDao.selectById(userId)).thenReturn(mockUser);
// When
User result = userService.getUserById(userId);
// Then
assertNotNull(result);
assertEquals(userId, result.getId());
verify(userDao, times(1)).selectById(userId);
}
@Test
@DisplayName("根据ID获取用户 - 参数为null")
public void testGetUserById_NullParameter() {
assertThrows(IllegalArgumentException.class, () -> {
userService.getUserById(null);
});
}
}equals()==SELECT *StringBuilderidcreate_timeupdate_timeThreadPoolExecutor