MyBatis与Spring MVC结合时,使用DAO注入出现:Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required


错误源自使用了这个例子:http://www.yihaomen.com/article/java/336.htm,如果运行时会出现如下错误:

Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required

以下是解决思路,参考:http://blog.csdn.net/xkhgnc_6666/article/details/52063713说的解决方法,分析如下:

1、从字面上意思理解是注入时导致了混乱,相同类型的Bean不知道是注入SqlSessionFactory还是SqlSessionTemplate。

2、可以使用@Qualifier注解和@Autowired注解通过指定哪一个真正的Bean将会被装配来消除混乱,参考:http://wiki.jikexueyuan.com/project/spring/annotation-based-configuration/spring-qualifier-annotation.html,也就是具体指定使用上面的哪一个进行Bean注入。

具体解决代码,在DAO中加入如下代码:

    @Autowired(required = false)
    @Qualifier("sqlSessionFactory") 
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }

还可以这样写:

    @Autowired(required = false)
    public void setSqlSessionFactory(
            @Qualifier("sqlSessionFactory")
            SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }

效果都是一样的。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM