MyBatis-Spring配置
一、XML方式配置
1.MapperFactoryBean
<!-- 创建被代理dao的代理对象 MapperFactoryBean会调用getObject创建代理对象getMapper()-->
<bean id="testdao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-- 指向需要被代理的接口-->
<property name="mapperInterface" value="被代理的接口全路径"></property>
</bean>
2.MapperScannerConfigurer
扫描指定包(全路径)下的dao接口,生成该接口代理类存储起来
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="dao包全路径"></property>
</bean>
二、Mapper注解
在dao类上配置mapper注解.需要在所有接口上配置该注解
@Mapper
public interface xxxDao {}
三、MapperScan
配置在springboot启动类,启动时项目会自动扫描对应包路径的dao接口注册到容器,类似于xml配置的MapperScannerConfigurer
@MapperScan("dao包层全路径")
@SpringBootApplication
public class SpringBootProjectApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootProjectApplication.class, args);
}
}
四、自动注入的注解
@Autowired
优先通过byType去容器中找对应的bean,如果没有再用byName.
如果编译期间无法找到.可以用通过@Autowired(required=false)来指定不检查该bean
@Resource
优先通过byName去容器中找对应的bean,如果没有再用byType
@Qualifier(“指定bean名”)
和@Autowired搭配使用的。如果bean的名字和属性对应不上,则可用@Qualifier来指定名称寻找bean