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



我的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.

根据我的理解,在这种情况下,我不应该在运行单元测试时看到这个被调用,因为我没有更改默认配置文件。但事实并非如此,因为它仍在被调度,并且我看到输出

[test]

在我的控制台上,尽管我尽了最大的努力来阻止它。发生了什么?为什么即使使用不同的活动配置文件,它仍然在运行?

更新:由于这是一份与工作相关的申请,我不能提供更多,但我会尽我所能。

类是这样配置的:

@Configuration
@EnableScheduling
public class BatchConfiguration {

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

@SpringApplicationConfiguration(classes = SpringBatchJsontestApplication.class)
public class SpringBatchJsontestApplicationTests extends AbstractTestNGSpringContextTests {

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

@SpringBootApplication
public class SpringBatchJsontestApplication {

它们都没有改变任何其他东西。没有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()));
      }
    };
  }

下面是触发测试概要文件的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>

@Profile注释对常规方法和用@Scheduled注释的方法没有任何作用。javadoc声明

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

  • 作为类型级注释在任何直接或间接用@Component注释的类上,包括@Configuration
  • 作为元注释,用于组合自定义原型注释
  • 作为任何@Bean方法的方法级注释

最后一种情况,用粗体表示,是@Profile在方法上的唯一使用。

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

最新更新