When I create 2 beans with @StepScope
and apply @Order
then the order for both beans still gets resolved to Ordered.LOWEST_PRECEDENCE
when trying to autowire them as a List.
@Bean
@Order(1)
@StepScope
public MyBean bean1(
return new MyBean("1");
}
@Bean
@Order(2)
@StepScope
public MyBean bean2(
return new MyBean("2");
}
Looking in OrderComparator
I see the beans are resolved to a source of ScopedProxyFactoryBean
which returns a null order value. Wondering if Im doing something wrong here as I would expect the ordering to work correctly.
So the aim in to autowire an ordered list into another bean eg
@Component
public class OuterBean {
private List<MyBean> beans;
public OuterBean(List<MyBean> beans) {
this.beans = beans;
}
}
And I would expect the list to contain {bean1,bean2}
Step scoped beans need to be used in the scope of a running step. Here is an example:
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();
}
}
The complete code can be found here . This example prints:
bean = 1
bean = 2
which means step scoped beans have been injected in the right order.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.