Java SpringBoot 方法在错误的@Profile 下仍然@Scheduled?

Pau*_*ker 3 java spring spring-boot

我的application.properties文件将默认配置文件定义为,spring.profiles.active=test并且我有一个这样安排的方法:

  @Scheduled(initialDelay = 2500, fixedRate = 60 * 1000 * minutesRecheckRate)
  @Profile("loop")
  public void processingLoop() {
    System.out.println(Arrays.toString(env.getActiveProfiles()));
    //.. the rest is omitted for brevity.
Run Code Online (Sandbox Code Playgroud)

据我了解,在这些情况下,我不应该在运行单元测试时看到它被调用,因为我没有更改默认配置文件。事实证明并非如此,因为这仍在安排中,我看到了输出

[test]
Run Code Online (Sandbox Code Playgroud)

尽管我已尽最大努力防止它出现在我的控制台中。怎么了?为什么即使使用不同的活动配置文件仍然运行?

更新:由于这是一个与工作相关的应用程序,我不能提供更多,但我会尽我所能。

该类的配置如下:

@Configuration
@EnableScheduling
public class BatchConfiguration {
Run Code Online (Sandbox Code Playgroud)

单元测试都是这样注释的:

@SpringApplicationConfiguration(classes = SpringBatchJsontestApplication.class)
public class SpringBatchJsontestApplicationTests extends AbstractTestNGSpringContextTests {
Run Code Online (Sandbox Code Playgroud)

主要的应用程序类是这样的:

@SpringBootApplication
public class SpringBatchJsontestApplication {
Run Code Online (Sandbox Code Playgroud)

他们都没有改变其他任何东西。没有context.xml文件,这是一个 SpringBoot 应用程序,所以一切都只是注释。


这是对我来说非常有效的最终结果

  @Profile("test")
  @Bean(name = TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)
  @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  public ScheduledAnnotationBeanPostProcessor scheduleBeanProcessorOverride() {
    logger.info("Test Profile is active, overriding ScheduledAnnotationBeanPostProcessor to prevent annotations from running during tests.");
    return new ScheduledAnnotationBeanPostProcessor() {
      @Override
      protected void processScheduled(Scheduled scheduled, Method method, Object bean) {
        logger.info(String.format("Preventing scheduling for %s, %s, %s", scheduled, method, bean.getClass().getCanonicalName()));
      }
    };
  }
Run Code Online (Sandbox Code Playgroud)

这是触发测试配置文件的 POM 配置,因此我不再需要在我的application.properties.

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19</version>
    <configuration>
      <systemPropertyVariables>
        <spring.profiles.active>test</spring.profiles.active>
      </systemPropertyVariables>
    </configuration>
  </plugin>
Run Code Online (Sandbox Code Playgroud)

Sot*_*lis 6

该@Profile注释不会为一个普通的方法,也没有带注释的方法做任何事情@Scheduled。javadoc 指出

@Profile 注释可以通过以下任何一种方式使用:

  • 作为直接或间接用 注释的任何类的类型级注释@Component,包括@Configuration类
  • 作为元注释,用于编写自定义构造型注释
  • 作为任何@Bean方法的方法级注释

最后一种情况(以粗体显示)是@Profileon 方法的唯一用法。

如果要@Scheduled在特定配置文件下启用该行为,请注释包含它的 bean(定义)。