问题描述
我有一个包(比如 packagesToScan
),其中包含我希望用 @Entity
注释的类.
I've a package (say packagesToScan
) containing Classes that I wish to persist annotated with @Entity
.
在定义ApplicationContext
配置时,我做了如下操作.
While defining ApplicationContext
configuration, I've done as follows.
@Configuration
@EnableJpaRepositories("packagesToScan")
@EnableTransactionManagement
@PropertySource("server/jdbc.properties")
@ComponentScan("packagesToScan")
公共类 JpaContext {
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;
}
在开发过程中,我在 packagesToScan
中有一些类不满足持久性要求(例如没有主键等),因此我不允许运行测试,因为 ApplicationContext
设置失败.
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.
现在,有什么办法可以只扫描某些选定的类或忽略 packagesToScan
中的某些类?
Now,Is there any way that I can scan just some selected classes or ignore some classes within packagesToScan
?
推荐答案
我一直在尝试解决同样的问题,最终得到了如下解决方案:
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>
我意识到有一个 setEntityTypeFilters
函数 在 LocalSessionFactoryBean
类上,可用于过滤要包含哪些类.在这个例子中,我使用了 RegexPatternTypeFilter 但有 其他类型的过滤器.
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.
此示例显示了 xml 配置,但转换为基于 java 的配置应该很简单.
This example shows the xml configuration but it should be trivial to convert to java based configuration.
这篇关于扫描 PackagesToScan 时忽略一些类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!