@SpringBootTest导致@PostConstruct被调用两次

时间:2016-09-10 18:38:16

标签: java spring spring-boot

使用版本1.4的Spring Boot sone测试注释,弃用“赞成{@link SpringBootTest}”。

Hovewer简单地用新的注释替换已弃用的注释,对我造成一个奇怪的副作用,@ PostConstruct被调用两次。

所以我们假设它是在

之前
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {ApplicationTestContext.class})
@IntegrationTest
@Transactional
public class EmployeesControllerSpringTest {

@Inject
private EmployeeRepository employeeRepository;

@Inject
private VenueRepository venueRepository;

@Inject
private TestUtilDummyObjects dummyObjects;

@Inject
private MappingJackson2HttpMessageConverter jacksonMessageConverter;

@Inject
private EntityManager entityManager;

@Inject
private ExceptionTranslator exceptionTranslator;

private MockMvc mockMvc;

@PostConstruct
public void postConstruct() {

    EmployeesController sut = new EmployeesController(employeeRepository);

    mockMvc = MockMvcBuilders
            .standaloneSetup(sut)
            .setControllerAdvice(exceptionTranslator)
            .setMessageConverters(jacksonMessageConverter)
            .build();
}

因此,使用以下

重新使用已弃用的注释
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ApplicationTestContext.class})
@Transactional

导致@PostConstruct被调用两次。

也许有人可以建议,我做错了什么?

请参阅下面的ApplicationTestContext.class:

//@TestConfiguration
//@SpringBootConfiguration
@ComponentScan(excludeFilters = {@ComponentScan.Filter(type =    FilterType.REGEX,
    pattern = "somepath.*")})
@EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class,   MetricRepositoryAutoConfiguration.class})
@EnableConfigurationProperties({ApplicationProperties.class, LiquibaseProperties.class})
@EnableAspectJAutoProxy(proxyTargetClass = false)
public class ApplicationTestContext extends WebMvcConfigurerAdapter {

@Override
public void addFormatters(FormatterRegistry registry) {
    registry.addConverter(new LocalDateConverter(Constants.DATE_FORMAT));
    registry.addConverter(new LocalDateTimeConverter(Constants.DATE_TIME_FORMAT));
}

}

更新

在@bhantol sugestion(删除所有冗余和注释)之后,我试图运行官方样本https://spring.io/guides/gs/spring-boot/

只需下载源代码并将@Before更改为@PostConstruct,仍然会导致它被调用两次。

示例中的代码如下:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerIT {

@LocalServerPort
private int port;

private URL base;

@Autowired
private TestRestTemplate template;

//@Before
@PostConstruct
public void setUp() throws Exception {
    this.base = new URL("http://localhost:" + port + "/");
    System.out.println("");
}

@Test
public void getHello() throws Exception {
    ResponseEntity<String> response = template.getForEntity(base.toString(),
            String.class);
    assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
}
}

不确定,但似乎是一个潜在的错误。

0 个答案:

没有答案