1、背景
在非SDK开发时,我们在项目工程都用有启动类,为了使得操作数据库的Mapper能够注入Bean容器,我们通常会在启动类上添加一个扫秒Mapper文件所在包路径的注解@MapperScan,会帮我们将包下面的所有Mapper注入进IOC容器。
@SpringBootApplication(scanBasePackages = {"com.nxq.learn.*"})
@MapperScan("com.nxq.learn.infrastructure.repository.db.mapper")
public class TestApplicationStarter {
/**
* The entry point of application.
*
* @param args the input arguments
*/
public static void main(String[] args) {
SpringApplication.run(TestApplicationStarter.class, args);
}
}
在SDK开发时,我们没有启动类,因而在某些场景下需要操作数据库时,在SpringBoot项目中,我们会通过自动配置的方式实现。
2、配置类实现
/**
* 配置类
*
* @since 2023-03-01
*/
@Configuration // SpringBoot配置类
@ComponentScan("com.nxq.learn") // 扫描该包下的所有类
public class TestConfiguration {
/**
* TestConfiguration
*/
public TestConfiguration() {
}
/**
* TestPoMapper
*
* @param session SqlSession
* @return TestPoMapper
*/
@Bean
@Primary
public TestPoMapper testPoMapper(SqlSession session) {
session.getConfiguration().addMapper(TestPoMapper.class);
return session.getMapper(TestPoMapper.class);
}
/**
* UsePoMapper
*
* @param session SqlSession
* @return UsePoMapper
*/
@Bean
@Primary
@ConditionalOnBean(value = TestPoMapper.class) // 当IOC容器中有TestPoMapper时才能将UsePoMapper注入IOC容器
public UsePoMapper usePoMapper(SqlSession session) {
session.getConfiguration().addMapper(UsePoMapper.class);
return session.getMapper(UsePoMapper.class);
}
/**
* UseRepositoryImpl
*
* @return UseRepositoryImpl
*/
@Bean({"useRepository"})
@ConditionalOnBean(value = UsePoMapper.class)
@Primary
public UseRepository useRepositoryImpl() {
return new UseRepositoryImpl();
}
/**
* TestRepositoryImpl
*
* @return TestRepositoryImpl
*/
@Bean({"testRepository"})
@ConditionalOnBean(value = TestPoMapper.class)
@Primary
public TestRepository testRepositoryImpl() {
return new TestRepositoryImpl();
}
}
3、Mapper
/**
* TestPoMapper,在infrastructure包的mapper包下
*
* @since 2023-03-01
*/
@Mapper
public interface TestPoMapper extends BaseMapper<TestPo> {
}
/**
* UsePoMapper
*
* @since 2023-02-21
*/
@Mapper
public interface UsePoMapper extends BaseMapper<UsePo> {
}
4、Repository
/**
* TestRepository,在domain包的repository下
*
* @since 2023-03-01
*/
public interface TestRepository {
int save(TestAgg testAgg);
}
/**
* TestRepository,在domain包的repository下
*
* @since 2023-03-01
*/
public interface UseRepository {
int save(UseAgg useAgg);
}
5、RepositoryImpl
/**
* TestRepositoryImpl,在infrastructure包的impl包下
*
* @since 2023-02-23
*/
public class TestRepositoryImpl implements TestRepository {
@Autowired
private TestPoMapper mapper;
@Override
public int save(TestAgg testAgg) {
return mapper.insert(aggToPo(taskAgg));
}
}
/**
* UseRepositoryImpl,在infrastructure包的impl包下
*
* @since 2023-02-23
*/
public class UseRepositoryImpl implements UseRepository {
@Autowired
private UsePoMapper mapper;
@Override
public int save(UseAgg useAgg) {
return mapper.insert(aggToPo(useAgg));
}
}