⭐️前言
MyBatis作为一种优秀的持久层框架,在使用MyBatis的过程中,我们经常需要从配置文件中读取一些参数,以便在mapper文件中使用。本文将介绍在不使用传参的情况下,如何从Apollo配置中读取这些参数,以及在mapper文件中使用${}
语法引用这些属性。
✨在MyBatis中读取配置的两种方式
🍖使用mybatis-config.xml中的<properties>
标签
MyBatis本身并没有直接负责加载application.properties
或其他配置文件的功能。application.properties
文件通常是由你的应用程序的配置加载机制(比如Spring Boot)负责加载的。MyBatis通过<properties>
元素提供了一种方式,允许你在MyBatis配置文件中引用这些外部属性。
<configuration><properties resource="application.properties"/><!-- 其他配置 -->
</configuration>
这种方式可以将application.properties
文件中的配置加载到MyBatis的配置中,但是在这种情况下无法读取到Apollo中的配置。
🧀在MyBatis配置中添加配置信息
如果希望在加载application.properties
时一起加载Apollo中的配置,你可能需要考虑使用Apollo的客户端来获取配置,然后将这些配置传递给MyBatis。通过编程方式设置MyBatis配置对象中的属性来实现。
@Value("${restrict}")String district;@Bean("sqlSessionFactoryBean")public SqlSessionFactory sqlSessionFactoryBean() {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(multipleDataSource);bean.setTypeAliasesPackage("com.*.*.service.**.model");//将配置文件的配置,加载到mybatis的配置中Properties mybatisProperties = new Properties();mybatisProperties.setProperty("restrict.district",district);bean.setConfigurationProperties(mybatisProperties);// 添加XML目录ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();try {bean.setConfigLocation(resolver.getResource("classpath:/mybatis-config.xml"));Resource[] resourceArray = resolver.getResources("classpath*:com/*/*/service/**/mapper/house/**/*.xml");bean.setMapperLocations(resourceArray);return bean.getObject();} catch (Exception e) {throw new RuntimeException(e);}}
这种方式可以手动设置属性,包括从Apollo中读取的配置信息。
✌配置使用
<!-- MyBatis Mapper 文件中 -->
<select id="selectByDistrict" parameterType="map" resultType="YourResultType">SELECT *FROM your_tableWHERE district = ${restrict.district}
</select>
在上述示例中,${restrict.district}
就是引用Apollo中配置的属性值。
😜总结
通过本文的介绍,你可以了解在不使用传参的情况下,如何在MyBatis的mapper文件中读取Apollo中的配置信息。选择适合你项目的方式,确保能够正确读取到配置,提高系统的灵活性和可维护性。希望这篇博客能对你有所帮助。
请注意,这只是一种可能的解决方案,具体实现可能因项目结构和框架不同而有所差异。确保在应用启动时提前加载Apollo配置,以确保其他组件在初始化时能够正确访问到配置信息。