6

I am working on a Spring boot application that uses Spring JPA with PostgreSQL. I am using @SpringBootTest(classes = <my package>.Application.class) to initialize my unit test for a controller class.

The problem is that this is causing the entityManagerFactory bean (and many other objects related to jpa, datasource, jdbc, etc.) to be created which is not needed for unit tests. Is there a way to prevent Spring from automatically creating these objects till they are actually used the first time?

I spent a lot of time trying to load up only the beans I need for my unit test but ran into many errors. I am relatively new to Spring and I am hoping someone else has run into this before...and can help. I can post code snippets if needed.

Update: I am not sure if I should edit or answer my own question...choosing to edit since I ended up changing my approach to unit tests. I added this to my test config class.

  @Configuration
  @ComponentScan(basePackages = {"api.controller", "api.config", "api.utils"})
  public class TestControllerConfig {
  }

and I mocked out the service and repository classes.

4

1 回答 1

9

您可以使用的属性在 spring-boot 中禁用自动配置,如下所示:exclude@EnableAutoConfiguration

@Configuration
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class TestConfig {
}

@EnableAutoConfiguration文档:

如果类不在类路径上,您可以使用excludeName注解的属性并指定完全限定名称。最后,您还可以通过spring.autoconfigure.exclude属性控制要排除的自动配置类列表。

于 2017-01-29T08:52:46.770 回答