springboot service 用 @Autowired注入 mapper 为null

Service类

@Controller
public class AdminRoleService {
    @Autowired
    AdminRoleMapper adminRoleMapper;

    public AdminRole selectByPrimaryKey(Integer roleId) {
        AdminRole adminRole = adminRoleMapper.selectByPrimaryKey(10001);
        return adminRole;
    }
}

测试调用类

@Resource
AdminRoleService adminRoleService;

@Test
void contextLoads() {
    AdminRole adminRole = adminRoleService.selectByPrimaryKey(10001);
    log.info(adminRole.getTitle());
}

注意:调用有@Autowired的类,不能用new,否则Autowiredl类会出现null,应该用@Resource或@Autowired注入进来

@Resource与@Autowired注解区别

@Autowired 默认byName方式
@Resource 默认byName方式,如果找不到名字,会调用byType方式自动装配

@Autowired 通过 @Qualifier(value = “Address2”) 指定名称
@Resource 通过 @Resource(name = “Address2”) 指定名称

@Resource 比较强大,性能比较差

上一篇:RabbitMQ在实际项目中的应用


下一篇:@Autowired注解遇到多个类型匹配注入的方式