Java SpringBoot方法仍然@Scheduled在错误的@Profile下?
我的Java SpringBoot方法仍然@Scheduled在错误的@Profile下?,java,spring,spring-boot,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
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配置,因此我不再需要在我的应用程序.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>
org.apache.maven.plugins
maven surefire插件
2.19
测试
对于常规方法,或者使用@Scheduled
注释的方法,该注释不起任何作用。javadoc声明
@Profile注释可通过以下任一方式使用:
- 作为任何类上的类型级注释,直接或间接地使用
@组件
进行注释,包括@配置
类
- 作为元注释,用于编写自定义原型注释
- 作为任何
@Bean
方法上的方法级注释
最后一个粗体字是方法上唯一使用的@Profile
如果要在特定概要文件下启用@Scheduled
行为,请对包含该行为的bean(定义)进行注释。能否显示更多代码?周围的@Configuration
代码和单元测试?请使用有意义的配置注释显示您的上下文xml或其他代码。我想在这个例子中,我必须通过手动返回来手动短路该方法。。。或者jerry用aspectj操纵某些东西。谢谢你的澄清!将调度移动到单个类,用@Profile
和@Component
或类似的注释该类,您将获得所需的行为。正如M.Deinum所建议的,除了@Profile
,我还使用了以下答案: