前言
这段时间在使用SSM进行网站开发时出现了UnsatisfiedDependencyException异常,由于第一次进行项目开发,对于问题的筛选能力有限,UnsatisfiedDependencyException 初次出现时,查阅大量资料,没有实际解决问题,一度导致页面彻底崩溃。
沉下心来琢磨后,问题得到了解决,但没有记录解决的过程,后续开发过程中,UnsatisfiedDependencyException再次出现,对照过去解决的代码,了解到问题产生的原因,祝遇到相同问题的各位能够在这里找到问题的解决方法,或者解决思路
正文
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'contentController': Unsatisfied dependency expressed through field 'articleService': Error creating bean with name 'articleService': Unsatisfied dependency expressed through method 'setMapper' parameter 0: No qualifying bean of type 'blog.article.mapper.ArticleMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {} 这是异常的主要原因,主体异常为第一行提到的 UnsatisfiedDependencyException(依赖项不满足异常) 全文大概意思是: 创建名为 contentController 的 bean 时出错,创建名为 articleService 的bean 时出错,articleService 中的字段 setMapper(我用的是set注入的方式)在注入时没有合适的Bean可以注入。 这里的mapper就是dao
这里贴出类结构,方便大家观看
// 表示层
@Controller
@RequestMapping
public class ContentController {
@Autowired
private ArticleService articleService;
}
//业务层
@Service
public class ArticleService {
private ArticleMapper articleMapper;
@Autowired
public void setMapper(SqlSessionTemplate sqlSessionTemplate) {
this.articleMapper = sqlSessionTemplate.getMapper(ArticleMapper.class);
}
}
//数据层
@Repository
@Transactional
public interface ArticleMapper {
}
具体内容无所谓,这里的问题主要是 成员变量注入时产生的问题 可以发现,我的业务层使用的set方法中设置了 sqlSessionTemplate 形参,并在方法中,通过sqlSessionTemplate.getMapper()获取mapper实例。
经过我多次试验发现:导致UnsatisfiedDependencyException产生的原因是 SqlSessionFactoryBean 不能为 ArticleService 中的 mapper 分配 mapper 实例,原因可能是我没有为 ArticleMapper 添加 sqlSessionTemplate 成员变量导致的,为 Mapper类(Dao)添加 sqlSessionTemplate 成员变量应该可以解决问题(未实践,理论如此)。
废话了一大堆,本人的表达能力稍差,希望对各位有所帮助。
发布改文章是对自己进行深刻记忆,避免出现这种 [低级] 错误。
最后声明:方案不适用所有情况,理性分析