1.应用程序主入口屏蔽DataSourceAutoConfiguration.class
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
如果不屏蔽,程序会将mapper接口对应的mapper.xml中的sql都通过配置的数据源去执行,无法灵活切换,这样就变成单一数据源了;因此需要屏蔽该类。
2.增加多数据源配置类
@Configuration
@MapperScan(basePackages = "com.example.demo.common.mapper.yjtpt",sqlSessionFactoryRef = "yjtptSessionFactory")
public class YjtptDataSourceConfig {
@Bean("yjtptDataSource")
@ConfigurationProperties(prefix = "spring.datasource.yjtpt")
public DataSource getDataSource(){
return DataSourceBuilder.create().build();
}
@Bean("yjtptSessionFactory")
public SqlSessionFactory getSqlSessionFactory(@Qualifier("yjtptDataSource")DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
return sqlSessionFactoryBean.getObject();
}
}
2.1 @Configuration
该注解表示当前类为配置类,在Spring加载的时候会执行;
2.2 @MapperScan
该注解表示扫描Mapper的注解,在Spring加载的时候会执行;
2.2.1 参数:basePackages
该参数表示Spring加载时将会扫描的包,会将包中的Mapper接口创建对应的实现类对象,存入Spring容器,便于ioc;
2.2.2 参数:sqlSessionFactoryDef
该参数表示包中的Mapper接口对应的Mapper.xml中的sql将会通过sqlSessionFactoryDef指向的sqlSessionFactory实例对象去执行;
2.3 sqlSessionFactory对象的获取
2.3.1 获取数据源对象
2.3.1.1 @ConfigurationProperties
先通过方法创建一个DataSource数据源对象,并使用该注解将配置信息注入到对象中
2.3.1.1 参数:prefix
表示配置信息的前缀
2.3.2 @Bean("...")
将创建的实体类对象进行命名,并注入Spring容器
2.3.2 获取SqlSessionFactory对象
2.3.2.1 创建SqlSessionFactoryBean对象
2.3.2.1.1 设置数据源setDataSource(DataSource datasource)
通过@Qualifier("...")注解完成对DataSource对象的注入
2.3.2.1.2 设置Mapper.xml路径setMapperLocations
2.3.2.2 将SqlSessionFactoryBean对象转换成SqlSessionFactory对象
3.注意事项
由于启动类屏蔽了DataSourceAutoConfiguration.class,又通过配置类完成多数据源配置,就得做到每个mapper要被Spring容器扫描到,并且注入到Spring容器中,否则没扫描到,就注入不进Spring容器中,也就没办法通过@Autowired注解注入,如果要强制注入会报以下错:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field ytljagetMapper in com.example.demo.common.service.serviceImp.YtljagetServiceImp required a bean of type 'com.example.demo.common.mapper.yt.YtljagetMapper' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.demo.common.mapper.yt.YtljagetMapper' in your configuration.
4.总结
这个坑自己琢磨了半天,搜索了半天,都在说是Spring容器未找到mapper实例对象,当看了眼配置类和启动类,才恍然大悟!!!启动类屏蔽了数据源自动装配类,配置类自行设计数据源,规定要扫描的包,但是mapper不在规定的包下面,导致没有注入Spring容器,我还强制注入,就报这个错了,一言难尽!!!以下是我项目的错误文件框架图
以下是正确的文件框架图