Home > Architecture, Framework, Java, Programming, Technologies, 技術 > 當 Spring 2.5 遇上 Hibernate Annotations – 自動搜尋 classpath 內的 entity

當 Spring 2.5 遇上 Hibernate Annotations – 自動搜尋 classpath 內的 entity

November 24, 2007 (Saturday) Leave a comment Go to comments

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

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: