Mybaits users will often write code like the following:You can seeuserMapper
There’s a red warning. While there’s nothing wrong with the code itself and it works, it’s always a little gross to have a warning. This article analyzes the causes and lists several solutions to this warning.
The reason, as we all know, is that IDEA is smart enough to understand Spring’s context. However, UserMapper interface is Mybatis, IDEA can not understand. The @AutoWired annotation, by default, requires the dependency object (i.e. UserMapper) to exist. IDEA assumes that the instance/proxy of this object is null, so it gives a friendly hint.
The solution
When using the @Autowired annotation, if you want to allow null values, set required = false, like this:
@Autowired(required = false)
private UserMapper userMapper;
Copy the code
So there won’t be a warning. IDEA thinks userMapper is null and gives a warning. With required = false, the @AutoWired annotation is no longer used to verify that the userMapper exists. There wouldn’t have been a warning.
Conclusion: This approach is a bit of a pain in the ass. A large existing project, which references Mapper everywhere, cannot be filled with required = false… And it’s hard to see for starters/new employees that the required = false attribute is added just to address the IDEA warning.
Method 2: Replace @autowired with @resource like this:
@Resource
private UserMapper userMapper;
Copy the code
No more nasty warnings. If you’re interested in why, check out the Difference between @AutoWired and @Resource. Summary: It’s great, but if a project already uses @Autowired a lot and then changes to @Resource around as a warning, it’s a bit of a pain.
Method 3: Annotate the Mapper interface with @repository annotations like this:
@Repository
public interface UserMapper extends Mapper<User> {}Copy the code
Of course, it works if you replace @Repository with @Component. UserMapper = null; userMapper = null; Add @repository to cheat on your IDEA… Method 4: Use Lombok
Like this:
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TestService {
private finalUserMapper userMapper; . }Copy the code
Lombok generates code like this:
@Service
public class TestService {
private final UserMapper userMapper;
@Autowired
public TestService(final UserMapper userMapper) {
this.userMapper = userMapper; }... }Copy the code
But IDEA will still warn you if you write lombok-generated code by hand. The Lombok plugin for IDEA is confusing IDEA… So no hint…
Method 5: Turn off the IDEA warning
I haven’t tried, and I don’t have the motivation to try. IDEA without prompts has no soul, and I never modify any warning Settings of IDEA.
Method 6: Install mybatis plugin
Install mybatis Plugin to solve this problem.
Transfer: www.imooc.com/article/287…