gpt4 book ai didi

java - Spring Step Scoped beans不尊重@Order注释

转载 作者:行者123 更新时间:2023-12-01 16:42:30 24 4
gpt4 key购买 nike

当我使用@StepScope创建2个bean并应用@Order时,两个bean的顺序仍然解析为Ordered.LOWEST_PRECEDENCE尝试将它们 Autowiring 为列表。

@Bean
@Order(1)
@StepScope
public MyBean bean1(
return new MyBean("1");
}

@Bean
@Order(2)
@StepScope
public MyBean bean2(
return new MyBean("2");
}

查看OrderComparator,我发现这些bean 被解析为ScopedProxyFactoryBean 的源,该源返回空订单值。想知道我在这里是否做错了什么,因为我希望顺序能够正确工作。

因此,目标是将有序列表 Autowiring 到另一个 bean 中,例如

@Component   
public class OuterBean {
private List<MyBean> beans;
public OuterBean(List<MyBean> beans) {
this.beans = beans;
}
}

我希望列表包含{bean1,bean2}

最佳答案

步骤作用域 bean 需要在正在运行的步骤的作用域中使用。这是一个例子:

import java.util.List;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

@Configuration
public class MyJob {

@Bean
@Order(1)
@StepScope
public MyBean bean1() {
return new MyBean("1");
}

@Bean
@Order(2)
@StepScope
public MyBean bean2() {
return new MyBean("2");
}

@Bean
public OuterBean outerBean(List<MyBean> beans) {
return new OuterBean(beans);
}

@Bean
public Tasklet tasklet(OuterBean outerBean) {
return (contribution, chunkContext) -> {
outerBean.sayHello();
return RepeatStatus.FINISHED;
};
}

@Bean
public Job job(JobBuilderFactory jobs, StepBuilderFactory steps) {
return jobs.get("job")
.start(steps.get("step")
.tasklet(tasklet(null))
.build())
.build();
}

}

完整代码可见here 。此示例打印:

bean = 1
bean = 2

这意味着步骤作用域的 Bean 已按正确的顺序注入(inject)。

关于java - Spring Step Scoped beans不尊重@Order注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61836412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com