问题描述
使用SonarLint扫描代码时,报错如下
@Slf4j
@Service
@RequiredArgsConstructor
public class UserInfoService {
private final UserMapper userMapper;
@Transactional(readOnly = true)
public ResponseResult getUserInfo(String username) {
UserInfo userInfo = this.getUserInfoByUsername(username); // issue occur
if (userInfo == null) {
return ResponseResult.failure(StatusCode.MESSAGE, username + " does not exist, please input username again!");
} else {
return ResponseResult.success(userInfo);
}
}
@Transactional(readOnly = true)
public UserInfo getUserInfoByUsername(String username) {
return userMapper.getUserByUsername(username);
}
}
解决方案
第一步:引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>3.2.0</version>
</dependency>
第二步:enable 代理
@SpringBootApplication
@EnableAspectJAutoProxy(exposeProxy = true) // add config
public class WebSystemApplication {
public static void main(String[] args) {
SpringApplication.run(WebSystemApplication.class, args);
}
}
第三步:修复问题
@Slf4j
@Service
@RequiredArgsConstructor
public class UserInfoService {
private final UserMapper userMapper;
@Transactional(readOnly = true)
public ResponseResult getUserInfo(String username) {
UserInfoService u = (UserInfoService) AopContext.currentProxy(); // use proxy
UserInfo userInfo = u.getUserInfoByUsername(username);
if (userInfo == null) {
return ResponseResult.failure(StatusCode.MESSAGE, username + " does not exist, please input username again!");
} else {
return ResponseResult.success(userInfo);
}
}
@Transactional(readOnly = true)
public UserInfo getUserInfoByUsername(String username) {
return userMapper.getUserByUsername(username);
}
}