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

时间:2015-10-16 02:33:43

标签: 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.

根据我的理解,在这些情况下,我不应该在运行单元测试时看到这个被调用,因为我没有更改默认配置文件。结果并非如此,因为这仍然是预定的,我看到了输出

[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>

1 个答案:

答案 0 :(得分:4)

@Profile注释不会对常规方法执行任何操作,也不会对使用@Scheduled注释的方法执行任何操作。 javadoc陈述

  

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

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

最后一个案例,以粗体显示,是@Profile对方法的唯一用途。

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