使用Spring boot Mybatis进行依赖注入配置时,遇到很多问题,希望在applicationContext.xml中配置所有的依赖注入关系,倒腾了几次,才基本搞清楚:需要配置所有的类型,包括dataSource、sqlSessionFactory,并且需要为Mapper接口进行配置,还需要设置从项目配置文件中读取数据库的配置信息。
首先是dataSource的配置:
<context:component-scan base-package="com.example" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${spring.datasource.driver-class-name}" />
<property name="url" value="${spring.datasource.url}" />
<property name="username" value="${spring.datasource.username}" />
<property name="password" value="${spring.datasource.password}" />
</bean>
<context:property-placeholder location="application.properties" />
这里context是为了从配置文件application.properties中读取数据库的设置。这需要在xml文件中声明相应的名称空间:
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
>
然后是sqlSessionFactory:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
接下来是定义的Mapper接口,在代码中的定义如下:
package com.example;
import cn.jiagoushi.poemgame.poemservice.shared.PoemLine;
import cn.jiagoushi.poemgame.poemservice.shared.Poet;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
/**
*
* @author zhenl
*/
@Mapper
public interface PoemLineMapper {
@Select("SELECT * FROM POEMLINE")
List<PoemLine> getAll();
@Select("SELECT * FROM POEMLINE WHERE LineContent=#{line} ")
PoemLine GetPoemLine(@Param("line") String line);
@Select("SELECT * FROM POEMLINE WHERE PoemId=#{poemId} ")
List<PoemLine> GetPoemLineByPoemId(@Param("poemId") String poemId) ;
@Select("SELECT * FROM POET WHERE Name=#{name} ")
Poet GetPoetByName(@Param("name") String name);
}
这个接口在配置中对应的class是"org.mybatis.spring.mapper.MapperFactoryBean" ,定义如下:
<bean id="mapperbean" class="org.mybatis.spring.mapper.MapperFactoryBean" >
<property name="mapperInterface" value="com.example.PoemLineMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
接下来就可以定义使用这个接口的bean:
<bean id="duishicheckanswerbean" class="cn.jiagoushi.poemgame.domain.service.duishi.DuishiCheckAnswer">
<constructor-arg ref="mypoemservicebean"/>
</bean>
网友评论