Standard Annotation Support

对于 Spring TestContext Framework 的所有配置,以下注释都受支持,并具有标准语义。请注意,这些注释不适用于特定测试,可以在 Spring Framework 中的任何位置使用。

The following annotations are supported with standard semantics for all configurations of the Spring TestContext Framework. Note that these annotations are not specific to tests and can be used anywhere in the Spring Framework.

  • @Autowired

  • @Qualifier

  • @Value

  • @Resource (jakarta.annotation) if JSR-250 is present

  • @ManagedBean (jakarta.annotation) if JSR-250 is present

  • @Inject (jakarta.inject) if JSR-330 is present

  • @Named (jakarta.inject) if JSR-330 is present

  • @PersistenceContext (jakarta.persistence) if JPA is present

  • @PersistenceUnit (jakarta.persistence) if JPA is present

  • @Transactional (org.springframework.transaction.annotation) with limited attribute support

JSR-250 Lifecycle Annotations

在 Spring TestContext Framework 中,您可以在 ApplicationContext 中配置的任何应用程序组件上使用 @PostConstruct@PreDestroy,语义标准。但是,这些生命周期注释在实际测试类中使用有限。

In the Spring TestContext Framework, you can use @PostConstruct and @PreDestroy with standard semantics on any application components configured in the ApplicationContext. However, these lifecycle annotations have limited usage within an actual test class.

如果测试类中的一个方法带有 @PostConstruct 注解,那么该方法在底层测试框架的任何 before 方法之前运行(例如,带有 JUnit Jupiter 的 @BeforeEach),并适用于测试类中的每个测试方法。另一方面,如果测试类中的一个方法带有 @PreDestroy 注解,则该方法永远不会运行。因此,在测试类中,我们建议你使用底层测试框架的测试生命周期回调,而不是 @PostConstruct@PreDestroy

If a method within a test class is annotated with @PostConstruct, that method runs before any before methods of the underlying test framework (for example, methods annotated with JUnit Jupiter’s @BeforeEach), and that applies for every test method in the test class. On the other hand, if a method within a test class is annotated with @PreDestroy, that method never runs. Therefore, within a test class, we recommend that you use test lifecycle callbacks from the underlying test framework instead of @PostConstruct and @PreDestroy.