Call transactional methods via an injected dependency instead of directly via ‘this‘

问题描述

使用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);
    }
}

解决方案

第一步:引入依赖


    org.springframework.boot
    spring-boot-starter-aop
    3.2.0

第二步: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);
    }
}

你可能感兴趣的:(Spring,Boot,java,前端,数据库)