Spring batch scope issue while using spring boot

前端 未结 6 1186
感动是毒
感动是毒 2020-11-30 05:13

I\'m having Standalone spring batch job. This works perfectly fine when in JUNIT

@RunWith(SpringJUnit4ClassRunner.class)
//@SpringApplicationConfiguration(cl         


        
相关标签:
6条回答
  • 2020-11-30 05:34

    Michael's comment is working for me, I am also providing JavaConfig copy-paste alternative for lazy people like me :)

    @Bean
    public StepScope stepScope() {
        final StepScope stepScope = new StepScope();
        stepScope.setAutoProxy(true);
        return stepScope;
    }
    
    0 讨论(0)
  • 2020-11-30 05:35

    You can solve by 2 Ways:

    A.

    Use spring.main.allow-bean-definition-overriding=true in application.properties

    B.

    To solve spring boot batch scope issue and avoid the use of spring.main.allow-bean-definition-overriding=true:

    Solutions:

    Disable autoProxy of StepScope. To perform that use following code snippet as a reference:

    <bean id="stepScope" class="org.springframework.batch.core.scope.StepScope">
          <property name="autoProxy" value="false"/>
    </bean>
    

    Now perform following Spring bean configuration:

    A.)

    To configure step scope via XML-Based configuration:

     <bean id="userPreferences" class="com.foo.UserPreferences" scope="step">
       <aop:scoped-proxy/>
     </bean>
    

    B.)

    To configure step scope via Java-Based configuration:

    @StepScope
    @Component(value = "userPreferences")
    public class UserPreference {}
    
    0 讨论(0)
  • 2020-11-30 05:39

    Don't forget to configure

    spring.main.allow-bean-definition-overriding=true
    
    0 讨论(0)
  • 2020-11-30 05:44

    Simply adding @SpringBatchTest on your test class should works.

    0 讨论(0)
  • 2020-11-30 05:50

    This may be a bug (we're still investigating), however we do have a work around. The cause of this is that when using @EnableBatchProcessing the StepScope that is automatically configured assumes java config and therefore does not proxy the step scoped beans, causing them to be created too soon. The work around is to manually configure a StepScope in your XML configuration with the following configuration:

    <bean id="stepScope" class="org.springframework.batch.core.scope.StepScope">
        <property name="autoProxy" value="true"/>
    </bean>
    
    0 讨论(0)
  • 2020-11-30 05:53

    Seeing as you are using @RunWith(SpringRunner.class), declaring @TestExecutionListeners({..., StepScopeTestExecutionListener.class}) above your class will setup the scopes for you.

    Same with @TestExecutionListeners({..., JobScopeTestExecutionListener.class}) for jobScope.

    0 讨论(0)
提交回复
热议问题