学习Spring Boot再次踩坑!!!
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper mapper;
@Override
public User selectByPrimaryKey(Integer id) {
return mapper.selectByPrimaryKey(id);
}
}
写代码写到这里时,出现了Could not autowire. No beans of 'UserMapper' type found.
警告,虽然在注启动类中配置了@MapperScan
注解,不会在启动程序时出错,但是看着那个红线很难受啊。找不到办法!
现记录解决办法:
首先想看清自己的启动类上有没有@MapperScan(basePackages = "dao路径")
这个注解,如果没有,那么看下面的就是白扯!!! 因为没有这个注解,你根本就没办法启动你的程序
一:最简单的办法
在进行自动注入时,不用@Autowired
注解,直接使用Java提供的@Resouce
注解。这相当于欺骗idea工具
二:编写一个Spring配置文件,并在主启动类加上**@ImportSource(“文件在项目中的位置”)**注解
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="dao路径"/>
</bean>
</beans>
这个方法就是我们在SSM中的用法,直接使用配置文件进行配置
三:使用注解编写一个配置类
@Configuration
public class MyConfig {
@Autowired
private UserMapper mapper;
@Bean
public UserMapper userMapper(){
return mapper;
}
}
这种方法好像是Spring Boot推荐我们使用的一个方法
四:在mapper接口中加上一个@Repository
注解,将这个接口在Spring中标记为一个组件,放到容器中
五:使用@AutoWired注解,并使用它的required属性赋值为false,即@Autowired(required = false)
required属性为true时:若找到对应的Bean,则抛出异常,即我们出现的红线;
required属性为true时:不管是否找到对应的Bean,都不抛异常。
这几种方法,我用的最舒服的就是第一种方法,反正不会出现红线碍眼就行。
其他的方法就是各种麻烦:
第二种方法就是还原Spring本质,去编写Spring的配置文件。在学习SSM框架时,相信小伙伴们都写烦了吧【手动捂脸!】
第三种方法就是编写配置类,将mapper接口注入到ioc容器中,还是各种麻烦,不想写
第四种方法,比前两种方法要简单些,但实际上,当我们的mapper接口很多的时候还是会觉得很麻烦,毕竟每写一个mapper接口就要记得再去这个接口上写一个注解