+-
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状态

The @Profile annotation may be used in any of the following ways:

as a type-level annotation on any class directly or indirectly annotated with @Component, including @Configuration classes as a meta-annotation, for the purpose of composing custom stereotype annotations as a method-level annotation on any @Bean method

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

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

点击查看更多相关文章

转载注明原文:Java SpringBoot方法仍然在错误的@Profile下@Scheduled? - 乐贴网