Ignore some classes while scanning PackagesToScan

TheKojuEffect picture TheKojuEffect · Apr 30, 2013 · Viewed 7.9k times · Source

I've a package (say packagesToScan) containing Classes that I wish to persist annotated with @Entity.

While defining ApplicationContext configuration, I've done as follows.


@Configuration
@EnableJpaRepositories("packagesToScan")
@EnableTransactionManagement
@PropertySource("server/jdbc.properties")
@ComponentScan("packagesToScan")

public class JpaContext {

... // Other configurations ....

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setDataSource(this.dataSource());
    emf.setJpaVendorAdapter(this.jpaVendorAdapter());
    emf.setPackagesToScan("packagesToScan");
    emf.setJpaProperties(this.hibernateProperties());
    return emf;

 }

While developing, I've some classes within packagesToScan which doesn't satisfy requirements for persistence (like no primary keys etc) and due to this I'm not allowed to run test because of ApplicationContext setup failure.

Now, Is there any way that I can scan just some selected classes or ignore some classes within packagesToScan?

Answer

nilgun picture nilgun · Nov 23, 2015

I have been trying to solve the same problem and finally got a solution as below:

<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    <property name="packagesToScan" value="com.mycompany.bean"/>
    <property name="entityTypeFilters" ref="packagesToScanIncludeRegexPattern">
    </property>
    <property name="hibernateProperties">
        // ...
    </property>
</bean>

<bean id="packagesToScanIncludeRegexPattern" class="org.springframework.core.type.filter.RegexPatternTypeFilter" >
    <constructor-arg index="0" value="^(?!com.mycompany.bean.Test).*"/>
</bean>

I realized that there is a setEntityTypeFilters function on the LocalSessionFactoryBean class which can be used to filter which classes to be included. In this example I used RegexPatternTypeFilter but there are other types of filters as well.

Also note that the filters work with include semantics. In order to convert to exclude semantics I had to use negative lookahead in the regex.

This example shows the xml configuration but it should be trivial to convert to java based configuration.