springboot在用@Mapper导致注入出错

启动文件

@MapperScan("com.mapper")
@SpringBootApplication
public class Ch1105SpringbootApplication {

    public static void main(String[] args) {

        SpringApplication.run(Ch1105SpringbootApplication.class, args);
    }

}

com.domain.Account

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Account {
    private Integer id;
    private String username;
    private String balance;

}

com.mapper.AccountMapper

@Mapper
public interface AccountMapper {

    @Select("select * from account")
    public Account getById(Integer id);
}

com.servlet.AccountService

@Service
public class AccountService {

    @Autowired
    private AccountMapper accountMapper;

    public Account getId(Integer id){
        return accountMapper.getById(id);
    }

}

resources:application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=0213
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

测结果报错:

。。

主要错误:No qualifying bean of type 'com.servlet.AccountService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

错误信息是bean找不到,十有八九是启动类不是在最外面

你这不是mapper没扫描到,而是service没扫描到啊。你在启动类上加个

@ComponentScan(basePackages = {"你的包路径"})试试

这种可能是@Mapper这个注解,没有起作用. 使用@Repository这个注解将Mapper标记为Bean

确认2个地方:

1、MapperScan的包名路径是否完整,AccountMapper是否在对应包下面。

2、@Mapper的引用类名是否正确

可以远程看下吗,service使用的代码快可以看下吗,注解引用的包是否都正确

package com.servlet;

import com.domain.Account;
import com.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AccountServlet {
    @Autowired
    private AccountMapper accountMapper;

    public Account get(Integer id){
        return accountMapper.getById(id);
    }
}

 

看报错,明显是mapper没有被Spring容器管理,建议看下@Mapper是不是使用的ibatis下的,可能是使用错了包导致的

①建议@MapperScan("com.mapper")-->@MapperScan(basePackageClasses = {AccountMapper .class})

②@ComponentScan(basePackageClasses = {AccountServlet .class})

No qualifying bean of type 'com.servlet.AccountService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

有没有大佬懂