让spring的AnnotationSessionFactoryBean支持路径扫描

 

最近推出的 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="package.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 的大趨勢之下,想辦法制定規則以及將規則以自動化落實才是長久之計。

from:http://www.blogjava.net/errorfun/archive/2008/08/14/221889.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值