springboot自动(@Autowired)注入方式出错:Could not autowire. No beans of 'UserDao' type found.

@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注解,表明当需要创建类时,这个被注解的类是一个候选类,就像是举手。

猜你喜欢

转载自blog.csdn.net/txhljjb/article/details/87896769
今日推荐