Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore some classes while scanning PackagesToScan

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?

like image 402
TheKojuEffect Avatar asked Apr 30 '13 06:04

TheKojuEffect


People also ask

How do I exclude specific packages in spring boot?

You may use the exclude attribute with the annotation @SpringBootApplication.


1 Answers

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.

like image 115
nilgun Avatar answered Sep 21 '22 16:09

nilgun