Judking
Judking

Reputation: 6371

"Bean named XXX must be of type[XXX], but was actually of type[XXX]"

when I integrate spring and mybatis, I encountered a error output, saying that:

Bean named 'sqlSessionFactory' must be of type [org.mybatis.spring.SqlSessionFactoryBean], but was actually of type [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory]

here is my code snippet:

ApplicationContext context = new ClassPathXmlApplicationContext("spring_mybatis_integration/spring_config.xml");
    SqlSessionFactoryBean sqlSessionFactoryBean = context.getBean("sqlSessionFactory", org.mybatis.spring.SqlSessionFactoryBean.class);

here is my bean definition in xml:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="configLocation" value="spring_mybatis_integration/mybatis_config.xml"></property>
  <property name="dataSource" ref="dataSource"></property>
</bean>

as you can see, both in java code and in xml file, I associate the bean sqlSessionFactory with class org.mybatis.spring.SqlSessionFactoryBean, why does the error output tell me another non-relative class name org.apache.ibatis.session.defaults.DefaultSqlSessionFactory?

Thanks a lot!

Version Info:

Upvotes: 0

Views: 5581

Answers (1)

Boris Treukhov
Boris Treukhov

Reputation: 17774

There is no point to accessSqlSessionFactoryBean via dependency injection, normally we work with the objects created by the Factory Beans, not the Factory Beans themselves, in this case the Factory Bean returns a DefaultSqlSessionFactory instance.

See Customizing instantiation logic with the FactoryBean Interface

But if you really want to access the FactoryBean instance, you should use ampersand symbol & see Spring: Getting FactoryBean object instead of FactoryBean.getObject()

Yes, the concept of the Factory Beans that return factories may be a bit confusing, but that is how things work in Spring.

So it's likely SqlSessionFactory instead of the SqlSessionFactoryFactoryBean is what you want.

update: actually MyBatis even explained this in the documentation on SqlSessionFactoryBean

Note that SqlSessionFactoryBean implements Spring's FactoryBean interface (see section 3.8 of the Spring documentation). This means that the bean Spring ultimately creates is not the SqlSessionFactoryBean itself, but what the factory returns as a result of the getObject() call on the factory. In this case, Spring will build an SqlSessionFactory for you at application startup and store it with the name sqlSessionFactory

Upvotes: 1

Related Questions