
pageHelper的使用十分简单,无需手动添加任何注解,这是怎么做到的呢?
答案是,pageHelper使用了springboot的自动装配功能,springboot启动时自动装配pageHelper相关的bean。
Jar包分析 jar包概览 spring.factoriescom.github.pagehelper pagehelper-spring-boot-autoconfigure1.2.13
该文件配置了自动配置类,作用是:Springboot启动时会自动扫描所有jar包里的meta-INF目录下的spring.factories来自动加载bean对象到spring容器中。
# Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration= com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration自动配置类PageHelperAutoConfiguration.java
// 标识该类是配置类,类似xml配置文件,给容器中添加bean
@Configuration
// 当spring的applicationContext容器中存在SqlSessionFactory类的bean时,当前配置类生效。
@ConditionalOnBean(SqlSessionFactory.class)
// 使能PageHelperProperties类的ConfigurationProperties功能;
// 所有配置文件中可配置的属性都在PageHelperProperties中封装着。
@EnableConfigurationProperties(PageHelperProperties.class)
// 加载了MybatisAutoConfiguration配置类后,再加载当前配置类(PageHelperAutoConfiguration)
@AutoConfigureAfter(MybatisAutoConfiguration.class)
public class PageHelperAutoConfiguration {
@Autowired
private List sqlSessionFactoryList;
@Autowired
private PageHelperProperties properties;
@Bean
@ConfigurationProperties(prefix = PageHelperProperties.PAGEHELPER_PREFIX)
public Properties pageHelperProperties() {
return new Properties();
}
@PostConstruct
public void addPageInterceptor() {
PageInterceptor interceptor = new PageInterceptor();
Properties properties = new Properties();
//先把一般方式配置的属性放进去
properties.putAll(pageHelperProperties());
//在把特殊配置放进去,由于close-conn 利用上面方式时,属性名就是 close-conn 而不是 closeConn,所以需要额外的一步
properties.putAll(this.properties.getProperties());
interceptor.setProperties(properties);
for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
sqlSessionFactory.getConfiguration().addInterceptor(interceptor);
}
}
}