Spring 2.5以上 提倡使用 annotation 的方式取代 xml 的设定,这个部分几乎完全取代了 Spring Annotations 的功能,看來这个 project 应该已经沒有什么生存空间。但 spring annotations 的 hibernate module 所提供的 AutomaticAnnotationSessionFactoryBean 是一个很不错的功能。以往使用 Hibernate Annotations 时我们只能以 fully qualified class name 或 fully qualified 的 package name 來指定 entity class。通过 AutomaticAnnotationSessionFactoryBean 我们可以自动找到所有标识为 @javax.persistence.Entity 的 classes 自动加入到 hibernate 的 mapping classes。Spring 2.5 既然本身就可以自动搜寻到 @Component 以及相关的 bean class,那我们就应该做到@Entity 的自动搜索。
我按照 spring annotations 的做法,提供一个自製的 session factory bean:
import org.hibernate.HibernateException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.util.ClassUtils;
import javax.persistence.Entity;
import java.io.IOException;
/**
* Created on: 2007/11/24
*
* @author Alan She
*/
public class ClasspathScanningAnnotationSessionFactoryBean extends AnnotationSessionFactoryBean {
private static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";
private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
private MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
private final TypeFilter entityFilter = new AnnotationTypeFilter(Entity.class);
private String resourcePattern = DEFAULT_RESOURCE_PATTERN;
private String[] basePackages;
public void setBasePackages(String basePackages) {
this.basePackages = basePackages;
}
protected void postProcessAnnotationConfiguration(AnnotationConfiguration config) throws HibernateException {
for (String basePackage : basePackages) {
try {
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
ClassUtils.convertClassNameToResourcePath(basePackage) + "/" + this.resourcePattern;
Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
for (int i = 0; i < resources.length; i++) {
Resource resource = resources[i];
MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
if (isEntity(metadataReader)) {
String classFileFullPath = resource.getURL().getPath();
String basePackageResourcePath = ClassUtils.convertClassNameToResourcePath(basePackage);
int startIndex = classFileFullPath.indexOf(basePackageResourcePath);
final String classFilePath = classFileFullPath.substring(startIndex,
classFileFullPath.length() - ClassUtils.CLASS_FILE_SUFFIX.length());
Class entityClass = null;
try {
entityClass = ClassUtils.forName(ClassUtils.convertResourcePathToClassName(classFilePath));
} catch (ClassNotFoundException e) {
throw new HibernateException("Entity class not found during classpath scanning", e);
}
config.addAnnotatedClass(entityClass);
}
}
}
catch (IOException ex) {
throw new HibernateException("I/O failure during classpath scanning", ex);
}
}
}
private boolean isEntity(MetadataReader metadataReader) throws IOException {
if (entityFilter.match(metadataReader, this.metadataReaderFactory)) {
return true;
}
return false;
}
}
这个 class 的內容是以 Spring 2.5 的 ClassPathBeanDefinitionScanner 为骨干而來的。原理很简单,以 PathMatchingResourcePatternResolver 去找到所以 basePackage 下的 classes,一一比對是否有 annotate 了 @javax.persistence.Entity,如果有就加入到 session factory 的 annotationClass。
<bean id="sessionFactory" class="com.hibernate.ClasspathScanningAnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> </props> </property> <property name="basePackages"> <list> <value>package.model</value> </list> </property> </bean>
使用上也非常简单,跟一般 spring 宣告 session factory 一样,只需指定 basePackage 作为搜寻的范围即可。
自动搜寻有优点也有缺点,但一个个的去设定 entity 很很麻烦。有人可能会觉得万一如果我有在 classpath 里的 entity 又不想加入那不就只能全都用手动设定?其实如果想要有些弹性可以加入 include / exclude pattern 等东西,让设定更活。毕竟设定当时代已经慢慢过去,在 convention over configuration 的大趋勢之下,想办法制定规则以及將规则以自动化落实才是长久之计。