其他分享
首页 > 其他分享> > springboot service 用 @Autowired注入 mapper 为null

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 比较强大,性能比较差

标签:mapper,selectByPrimaryKey,调用,Resource,springboot,service,Autowired,AdminRole,adm
来源: https://blog.csdn.net/weixin_44371237/article/details/116698721