@Mapper
public interface UserDao {
/** * 通过名字查询用户信息 */
@Select("SELECT * FROM user WHERE name = #{name}")
User findUserByName(@Param("name") String name);
}
@Service
public class UserService {
@Autowired
private UserDao userDao;
/** * 根据名字查找用户 */
public User selectUserByName(String name) {
return userDao.findUserByName(name);
}
}
当我用@Autowired将private UserDao userDao自动注入时出现Could not autowire. No beans of 'UserDao' type found.
报错原因是UserDao的bean没有被找到。所以可以通过@Component注解来标记你要自动的类。如代码所示:
@Component
@Mapper
public interface UserDao {
/**
* 通过名字查询用户信息
*/
@Select("SELECT * FROM user WHERE name = #{name}")
User findUserByName(@Param("name") String name);
}
在某个类上使用@Component注解,表明当需要创建类时,这个被注解的类是一个候选类,就像是举手。
本文探讨了在使用@Autowired注解自动装配UserDao接口时遇到的“Could not autowire. No beans of 'UserDao' type found.”错误。文章详细解释了如何通过在UserDao接口上添加@Component和@Mapper注解来解决该问题,确保Spring可以正确扫描并实例化UserDao Bean。
2万+

被折叠的 条评论
为什么被折叠?



