场景
想在 Spring Boot 启动时使用 guava 缓存,将数据库的部分内容放入缓存中,所以写了一个 CacheConfig 类,但是在启动过程中报错,错误为:
@Configuration
public class CacheConfig {
}
Mapped Statements collection does not contain value for com.xxx.xxx.dao.ScoreDao.selectById
类似情况为:一个 person 关联了一个 score,拥有字段 scoreId(外键),并且在Person 类中有一个成员 Score score,使用 Mybatis 在查询 person 时一并将 score 查询出来。这段程序在之前已经运行测试成功。
Dao 中方法为:
PersonDao
@Select("select " + FIELDS + " from person")
@ResultMap("PersonMapper.PersonResult")
public List<Person> selectAll();
ScoreDao
@Select("select " + FIELDS + " from score where sid = #{sid}")
Score selectById(long sid);
Person ResultMap 在 xml 文件中配置为
<mapper namespace="SellerRelationMapper">
<resultMap type="SellerRelation" id="SellerRelationResult">
<id property="sid" column="sid"/>
<result property="scoreId" column="score_id"/>
<association property="score" column="score_id" select="com.xxx.xxx.dao.ScoreDao.selectById"/>
</resultMap>
</mapper>
原因
在执行 CacheConfig 类中方法时,ScoreDao 还没有被注入,所以无法被找到。
解决方法
原本想是否能控制依赖注入的顺序,让 CacheConfig 在 ScoreDao 被注入后再执行,但是没有查询到方案,于是只能在 CacheConfig 类或被 CacheConfig 类依赖的 Service 添加如下代码
@Autowired
private ScoreDao ScoreDao;