问:
SPRING-BATCH ERROR: No context holder available for step scope when using threadPoolExecutor in spring batch application
I am currently trying to read data from .dat file and persist it into database using spring batch. I have used threading method with step scope to improve my performance but it seems that spring is unable to create proxy bean for my method. I am getting java.lang.IllegalStateException: No context holder available for step scope error. I have referenced many questions and references but none seems to address my issue. Please provide me some useful reference or any hints to my problem. Thanks in advance...

MyConfiguration.java

```<code>@Configuration
public class MyBatchConfiguration
{
    @Autowired
    JobBuilderFactory jobBuilderFactory;

    @Autowired
    StepBuilderFactory stepBuilderFactory;

    @Bean(name="commonJobCompletionListener")
    public JobCompletionNotificationListener jobCompletionlistener()
    {
        return new JobCompletionNotificationListener();
    }

    @Bean(name="commonTaskExecutor")
    @Scope(value="step", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public ThreadPoolTaskExecutor taskExecutor()
    {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(3);
        executor.setMaxPoolSize(5);
        return executor;
    }

    @Bean(name="cstarU2NavReader")
    @Scope(value="step", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public FlatFileItemReader<CSTARU2NAVInputMapperDTO> reader(@Value("#{jobParameters['fileName']}") String fileName) throws IOException
    {
        FlatFileItemReader<CSTARU2NAVInputMapperDTO> newBean = new FlatFileItemReader<>();
        newBean.setName("fileReader");
        newBean.setResource(new InputStreamResource(FileUtils.openInputStream(new File(fileName))));
        newBean.setLineMapper(lineMapper());
        newBean.setLinesToSkip(1);
        return newBean;
    }

    @Bean(name="cstarU2NavLineMapper")
    public DefaultLineMapper<CSTARU2NAVInputMapperDTO> lineMapper()
    {
        DefaultLineMapper<CSTARU2NAVInputMapperDTO> lineMapper = new DefaultLineMapper<>();
        lineMapper.setLineTokenizer(lineTokenizer());
        CSTARU2NAVReader cstarU2NavReader = new CSTARU2NAVReader();
        lineMapper.setFieldSetMapper(cstarU2NavReader);
        return lineMapper;
    }

    @Bean(name="cstarU2NavTokenizer")
    public DelimitedLineTokenizer lineTokenizer()
    {
        DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
        tokenizer.setDelimiter("|");
        tokenizer.setNames("field1","field12","field13","field14");
        tokenizer.setIncludedFields(0,2,3,5);
        return tokenizer;
    }

    @Bean(name="cstarU2NavBatchProcessor")
    public ItemProcessor<CSTARU2NAVInputMapperDTO, IntReplNav> processor()
    {
        return new CSTARU2NAVProcessor();
    }

    @Bean(name="cstarU2NavBatchWriter")
    public ItemWriter<IntReplNav> writer()
    {
        return new CSTARU2NAVWriter();
    }

    @Bean(name="cstarU2NavStep")
    public Step step1() throws IOException
    {
        return stepBuilderFactory.get("cstarU2NavStep")
                .<CSTARU2NAVInputMapperDTO, IntReplNav>chunk(10)
                .reader(this.reader(null))
                .processor(this.processor())
                .writer(this.writer())
                .taskExecutor(this.taskExecutor())
                .build();
    }

    @Bean(name="cstarU2NavFileImportJob")
    public Job importUserJob(@Autowired @Qualifier("cstarU2NavStep") Step step1)
    {
        return jobBuilderFactory
                .get("cstarU2NavFileImportJob"+new Date())
                .incrementer(new RunIdIncrementer())
                .listener(this.jobCompletionlistener())
                .flow(step1)
                .end()
                .build();
    }

}
</code>```

JobCompletionNotificationListener.java

```<code>public class JobCompletionNotificationListener extends JobExecutionListenerSupport
{

    @Autowired
    ThreadPoolTaskExecutor taskExecutor;

    @Override
    public void afterJob(JobExecution jobExecution)
    {
        if(jobExecution.getStatus() == BatchStatus.COMPLETED)
        {
            taskExecutor.shutdown();
        }
    }

}

</code>```

ErrorLog

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.commonTaskExecutor': Scope 'step' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No context holder available for step scope
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:362) ~[spring-beans-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:672) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor$$EnhancerBySpringCGLIB$$621affe0.shutdown(<generated>) ~[spring-context-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at com.capgroup.horizon.pricecapture.listener.JobCompletionNotificationListener.afterJob(JobCompletionNotificationListener.java:20) ~[classes/:?]
    at org.springframework.batch.core.listener.CompositeJobExecutionListener.afterJob(CompositeJobExecutionListener.java:60) ~[spring-batch-core-4.0.2.RELEASE.jar:4.0.2.RELEASE]
    at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:354) ~[spring-batch-core-4.0.2.RELEASE.jar:4.0.2.RELEASE]
    at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:144) ~[spring-batch-core-4.0.2.RELEASE.jar:4.0.2.RELEASE]
    at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) ~[spring-core-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:137) ~[spring-batch-core-4.0.2.RELEASE.jar:4.0.2.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_144]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_144]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_144]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_144]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) ~[spring-batch-core-4.0.2.RELEASE.jar:4.0.2.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at com.sun.proxy.$Proxy122.run(Unknown Source) ~[?:?]
    at com.capgroup.horizon.pricecapture.services.impl.CSTARU2NAVFileServiceImpl.process(CSTARU2NAVFileServiceImpl.java:34) ~[classes/:?]
    at com.capgroup.horizon.pricecapture.services.impl.CSTARU2NAVFileServiceImpl$$FastClassBySpringCGLIB$$b9bdc800.invoke(<generated>) ~[classes/:?]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at net.bull.javamelody.MonitoringSpringInterceptor.invoke(MonitoringSpringInterceptor.java:76) ~[javamelody-core-1.74.0.jar:1.74.0]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at com.capgroup.horizon.pricecapture.services.impl.CSTARU2NAVFileServiceImpl$$EnhancerBySpringCGLIB$$76b5d896.process(<generated>) ~[classes/:?]
    at com.capgroup.horizon.pricecapture.services.impl.FileProcessServiceImpl.processFile(FileProcessServiceImpl.java:71) ~[classes/:?]
    at com.capgroup.horizon.pricecapture.services.impl.FileProcessServiceImpl.execute(FileProcessServiceImpl.java:56) ~[classes/:?]
    at com.capgroup.horizon.pricecapture.services.impl.FileProcessServiceImpl$$FastClassBySpringCGLIB$$6a723fea.invoke(<generated>) ~[classes/:?]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at net.bull.javamelody.MonitoringSpringInterceptor.invoke(MonitoringSpringInterceptor.java:76) ~[javamelody-core-1.74.0.jar:1.74.0]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at com.capgroup.horizon.pricecapture.services.impl.FileProcessServiceImpl$$EnhancerBySpringCGLIB$$d2008294.execute(<generated>) ~[classes/:?]
    at com.capgroup.horizon.pricecapture.controllers.BatchController.fileProcess(BatchController.java:36) ~[classes/:?]
    at com.capgroup.horizon.pricecapture.controllers.BatchController$$FastClassBySpringCGLIB$$50364d5.invoke(<generated>) ~[classes/:?]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at net.bull.javamelody.MonitoringSpringInterceptor.invoke(MonitoringSpringInterceptor.java:76) ~[javamelody-core-1.74.0.jar:1.74.0]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at com.capgroup.horizon.pricecapture.controllers.BatchController$$EnhancerBySpringCGLIB$$2350dc35.fileProcess(<generated>) ~[classes/:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_144]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_144]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_144]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_144]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:891) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:873) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:858) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.zalando.logbook.servlet.NormalStrategy.doFilter(NormalStrategy.java:38) ~[logbook-servlet-1.12.1.jar:?]
    at org.zalando.logbook.servlet.LogbookFilter.doFilter(LogbookFilter.java:39) ~[logbook-servlet-1.12.1.jar:?]
    at org.zalando.logbook.servlet.HttpFilter.doFilter(HttpFilter.java:31) ~[logbook-servlet-1.12.1.jar:?]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:239) ~[javamelody-core-1.74.0.jar:1.74.0]
    at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:215) ~[javamelody-core-1.74.0.jar:1.74.0]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[?:1.8.0_144]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[?:1.8.0_144]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at java.lang.Thread.run(Thread.java:748) [?:1.8.0_144]
Caused by: java.lang.IllegalStateException: No context holder available for step scope
    at org.springframework.batch.core.scope.StepScope.getContext(StepScope.java:167) ~[spring-batch-core-4.0.2.RELEASE.jar:4.0.2.RELEASE]
    at org.springframework.batch.core.scope.StepScope.get(StepScope.java:99) ~[spring-batch-core-4.0.2.RELEASE.jar:4.0.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:350) ~[spring-beans-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    ... 112 more
</code>```

Link for sample project to reproduce the above issue : https://github.com/Anand450623/Spring-Batch

答:
You need to add @EnableBatchProcessing annotation on your configuration class or manually declare the Step scope in your application context:

```<code>@Bean
public StepScope stepScope() {
    StepScope stepScope = new StepScope();
    stepScope.setAutoProxy(false);
    return stepScope;
}
</code>```

Body:
I am currently trying to read data from .dat file and persist it into database using spring batch. I have used threading method with step scope to improve my performance but it seems that spring is unable to create proxy bean for my method. I am getting java.lang.IllegalStateException: No context holder available for step scope error. I have referenced many questions and references but none seems to address my issue. Please provide me some useful reference or any hints to my problem. Thanks in advance...

MyConfiguration.java

@Configuration
public class MyBatchConfiguration
{
    @Autowired
    JobBuilderFactory jobBuilderFactory;

    @Autowired
    StepBuilderFactory stepBuilderFactory;

    @Bean(name="commonJobCompletionListener")
    public JobCompletionNotificationListener jobCompletionlistener()
    {
        return new JobCompletionNotificationListener();
    }

    @Bean(name="commonTaskExecutor")
    @Scope(value="step", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public ThreadPoolTaskExecutor taskExecutor()
    {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(3);
        executor.setMaxPoolSize(5);
        return executor;
    }

    @Bean(name="cstarU2NavReader")
    @Scope(value="step", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public FlatFileItemReader<CSTARU2NAVInputMapperDTO> reader(@Value("#{jobParameters['fileName']}") String fileName) throws IOException
    {
        FlatFileItemReader<CSTARU2NAVInputMapperDTO> newBean = new FlatFileItemReader<>();
        newBean.setName("fileReader");
        newBean.setResource(new InputStreamResource(FileUtils.openInputStream(new File(fileName))));
        newBean.setLineMapper(lineMapper());
        newBean.setLinesToSkip(1);
        return newBean;
    }

    @Bean(name="cstarU2NavLineMapper")
    public DefaultLineMapper<CSTARU2NAVInputMapperDTO> lineMapper()
    {
        DefaultLineMapper<CSTARU2NAVInputMapperDTO> lineMapper = new DefaultLineMapper<>();
        lineMapper.setLineTokenizer(lineTokenizer());
        CSTARU2NAVReader cstarU2NavReader = new CSTARU2NAVReader();
        lineMapper.setFieldSetMapper(cstarU2NavReader);
        return lineMapper;
    }

    @Bean(name="cstarU2NavTokenizer")
    public DelimitedLineTokenizer lineTokenizer()
    {
        DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
        tokenizer.setDelimiter("|");
        tokenizer.setNames("field1","field12","field13","field14");
        tokenizer.setIncludedFields(0,2,3,5);
        return tokenizer;
    }

    @Bean(name="cstarU2NavBatchProcessor")
    public ItemProcessor<CSTARU2NAVInputMapperDTO, IntReplNav> processor()
    {
        return new CSTARU2NAVProcessor();
    }

    @Bean(name="cstarU2NavBatchWriter")
    public ItemWriter<IntReplNav> writer()
    {
        return new CSTARU2NAVWriter();
    }

    @Bean(name="cstarU2NavStep")
    public Step step1() throws IOException
    {
        return stepBuilderFactory.get("cstarU2NavStep")
                .<CSTARU2NAVInputMapperDTO, IntReplNav>chunk(10)
                .reader(this.reader(null))
                .processor(this.processor())
                .writer(this.writer())
                .taskExecutor(this.taskExecutor())
                .build();
    }

    @Bean(name="cstarU2NavFileImportJob")
    public Job importUserJob(@Autowired @Qualifier("cstarU2NavStep") Step step1)
    {
        return jobBuilderFactory
                .get("cstarU2NavFileImportJob"+new Date())
                .incrementer(new RunIdIncrementer())
                .listener(this.jobCompletionlistener())
                .flow(step1)
                .end()
                .build();
    }

}

JobCompletionNotificationListener.java

public class JobCompletionNotificationListener extends JobExecutionListenerSupport
{

    @Autowired
    ThreadPoolTaskExecutor taskExecutor;

    @Override
    public void afterJob(JobExecution jobExecution)
    {
        if(jobExecution.getStatus() == BatchStatus.COMPLETED)
        {
            taskExecutor.shutdown();
        }
    }

}

ErrorLog

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.commonTaskExecutor': Scope 'step' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No context holder available for step scope
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:362) ~[spring-beans-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:672) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor$$EnhancerBySpringCGLIB$$621affe0.shutdown(<generated>) ~[spring-context-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at com.capgroup.horizon.pricecapture.listener.JobCompletionNotificationListener.afterJob(JobCompletionNotificationListener.java:20) ~[classes/:?]
    at org.springframework.batch.core.listener.CompositeJobExecutionListener.afterJob(CompositeJobExecutionListener.java:60) ~[spring-batch-core-4.0.2.RELEASE.jar:4.0.2.RELEASE]
    at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:354) ~[spring-batch-core-4.0.2.RELEASE.jar:4.0.2.RELEASE]
    at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:144) ~[spring-batch-core-4.0.2.RELEASE.jar:4.0.2.RELEASE]
    at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) ~[spring-core-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:137) ~[spring-batch-core-4.0.2.RELEASE.jar:4.0.2.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_144]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_144]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_144]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_144]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) ~[spring-batch-core-4.0.2.RELEASE.jar:4.0.2.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at com.sun.proxy.$Proxy122.run(Unknown Source) ~[?:?]
    at com.capgroup.horizon.pricecapture.services.impl.CSTARU2NAVFileServiceImpl.process(CSTARU2NAVFileServiceImpl.java:34) ~[classes/:?]
    at com.capgroup.horizon.pricecapture.services.impl.CSTARU2NAVFileServiceImpl$$FastClassBySpringCGLIB$$b9bdc800.invoke(<generated>) ~[classes/:?]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at net.bull.javamelody.MonitoringSpringInterceptor.invoke(MonitoringSpringInterceptor.java:76) ~[javamelody-core-1.74.0.jar:1.74.0]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at com.capgroup.horizon.pricecapture.services.impl.CSTARU2NAVFileServiceImpl$$EnhancerBySpringCGLIB$$76b5d896.process(<generated>) ~[classes/:?]
    at com.capgroup.horizon.pricecapture.services.impl.FileProcessServiceImpl.processFile(FileProcessServiceImpl.java:71) ~[classes/:?]
    at com.capgroup.horizon.pricecapture.services.impl.FileProcessServiceImpl.execute(FileProcessServiceImpl.java:56) ~[classes/:?]
    at com.capgroup.horizon.pricecapture.services.impl.FileProcessServiceImpl$$FastClassBySpringCGLIB$$6a723fea.invoke(<generated>) ~[classes/:?]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at net.bull.javamelody.MonitoringSpringInterceptor.invoke(MonitoringSpringInterceptor.java:76) ~[javamelody-core-1.74.0.jar:1.74.0]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at com.capgroup.horizon.pricecapture.services.impl.FileProcessServiceImpl$$EnhancerBySpringCGLIB$$d2008294.execute(<generated>) ~[classes/:?]
    at com.capgroup.horizon.pricecapture.controllers.BatchController.fileProcess(BatchController.java:36) ~[classes/:?]
    at com.capgroup.horizon.pricecapture.controllers.BatchController$$FastClassBySpringCGLIB$$50364d5.invoke(<generated>) ~[classes/:?]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at net.bull.javamelody.MonitoringSpringInterceptor.invoke(MonitoringSpringInterceptor.java:76) ~[javamelody-core-1.74.0.jar:1.74.0]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at com.capgroup.horizon.pricecapture.controllers.BatchController$$EnhancerBySpringCGLIB$$2350dc35.fileProcess(<generated>) ~[classes/:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_144]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_144]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_144]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_144]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:891) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:873) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:858) ~[spring-webmvc-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.zalando.logbook.servlet.NormalStrategy.doFilter(NormalStrategy.java:38) ~[logbook-servlet-1.12.1.jar:?]
    at org.zalando.logbook.servlet.LogbookFilter.doFilter(LogbookFilter.java:39) ~[logbook-servlet-1.12.1.jar:?]
    at org.zalando.logbook.servlet.HttpFilter.doFilter(HttpFilter.java:31) ~[logbook-servlet-1.12.1.jar:?]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:239) ~[javamelody-core-1.74.0.jar:1.74.0]
    at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:215) ~[javamelody-core-1.74.0.jar:1.74.0]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[?:1.8.0_144]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[?:1.8.0_144]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-8.5.37.jar:8.5.37]
    at java.lang.Thread.run(Thread.java:748) [?:1.8.0_144]
Caused by: java.lang.IllegalStateException: No context holder available for step scope
    at org.springframework.batch.core.scope.StepScope.getContext(StepScope.java:167) ~[spring-batch-core-4.0.2.RELEASE.jar:4.0.2.RELEASE]
    at org.springframework.batch.core.scope.StepScope.get(StepScope.java:99) ~[spring-batch-core-4.0.2.RELEASE.jar:4.0.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:350) ~[spring-beans-5.0.12.RELEASE.jar:5.0.12.RELEASE]
    ... 112 more

Link for sample project to reproduce the above issue : https://github.com/Anand450623/Spring-Batch

Body:
You need to add @EnableBatchProcessing annotation on your configuration class or manually declare the Step scope in your application context:

@Bean
public StepScope stepScope() {
    StepScope stepScope = new StepScope();
    stepScope.setAutoProxy(false);
    return stepScope;
}


来源: stackexchange

问:
jquery select table columns
I am working on selecting a specific table's cells.

Some cells have a class of "testOff", and I'm attempting to change the table row to a different color, if the class exists.

here's what I have so far:

```<code>$("table#customersTable td.testOff").each(function(){

    $(this).closest("tr").css("background-color","#F6CCDA");

});
</code>```

I must be missing something, since it's not showing the background color for any of the cells.
Does anyone see an error with how I'm selecting?

答:
```<code>$('#customersTable td.testOff').closest('tr').addClass('highlightColour').css("background-color","#F6CCDA");
</code>```

working demo

ContentLicense: CC BY-SA 3.0

Title: jquery select table columns

Body:
I am working on selecting a specific table's cells.

Some cells have a class of "testOff", and I'm attempting to change the table row to a different color, if the class exists.

here's what I have so far:

$("table#customersTable td.testOff").each(function(){

    $(this).closest("tr").css("background-color","#F6CCDA");

});

I must be missing something, since it's not showing the background color for any of the cells.
Does anyone see an error with how I'm selecting?

Body:
$('#customersTable td.testOff').closest('tr').addClass('highlightColour').css("background-color","#F6CCDA");

working demo


问:
OpenJDK 10 rejects all SSL certificates
I installed OpenJDK 10. What I did was just unpack it, set the PATH variable and the JAVA_HOME variable.

Java even rejects the certificate of google.de (and all others I tried). I tested this by some dummy class that tries to connect. Outcome is:

```<code>C:\Users\Alexander\Downloads>java SSLPoke google.de 443
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
        at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:290)
        at java.base/sun.security.validator.Validator.validate(Validator.java:264)
        at java.base/sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:343)
        at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:226)
        at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:133)
        at java.base/sun.security.ssl.ClientHandshaker.checkServerCerts(ClientHandshaker.java:1947)
        at java.base/sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1777)
        at java.base/sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:264)
        at java.base/sun.security.ssl.Handshaker.processLoop(Handshaker.java:1098)
        at java.base/sun.security.ssl.Handshaker.processRecord(Handshaker.java:1026)
        at java.base/sun.security.ssl.SSLSocketImpl.processInputRecord(SSLSocketImpl.java:1137)
        at java.base/sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1074)
        at java.base/sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
        at java.base/sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1402)
        at java.base/sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:733)
        at java.base/sun.security.ssl.AppOutputStream.write(AppOutputStream.java:67)
        at java.base/sun.security.ssl.AppOutputStream.write(AppOutputStream.java:81)
        at SSLPoke.main(SSLPoke.java:31)
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at java.base/sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
        at java.base/sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
        at java.base/java.security.cert.CertPathBuilder.build(CertPathBuilder.java:297)
        at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
        ... 18 more
</code>```

Found a lot on the net how to add special certs to java but i think in my java installation something is wrong in general.

So my question is what could cause such a thing???

答:
Ended up installing oracle jdk 10 (also 10.0.2) and that works </p>

```<code>C:\Users\Alexander\Downloads>java "SSLPoke" google.de 443
Successfully connected
</code>```

ContentLicense: CC BY-SA 4.0

Title: OpenJDK 10 rejects all SSL certificates

Body:
I installed OpenJDK 10. What I did was just unpack it, set the PATH variable and the JAVA_HOME variable.

Java even rejects the certificate of google.de (and all others I tried). I tested this by some dummy class that tries to connect. Outcome is:

C:\Users\Alexander\Downloads>java SSLPoke google.de 443
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
        at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:290)
        at java.base/sun.security.validator.Validator.validate(Validator.java:264)
        at java.base/sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:343)
        at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:226)
        at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:133)
        at java.base/sun.security.ssl.ClientHandshaker.checkServerCerts(ClientHandshaker.java:1947)
        at java.base/sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1777)
        at java.base/sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:264)
        at java.base/sun.security.ssl.Handshaker.processLoop(Handshaker.java:1098)
        at java.base/sun.security.ssl.Handshaker.processRecord(Handshaker.java:1026)
        at java.base/sun.security.ssl.SSLSocketImpl.processInputRecord(SSLSocketImpl.java:1137)
        at java.base/sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1074)
        at java.base/sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
        at java.base/sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1402)
        at java.base/sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:733)
        at java.base/sun.security.ssl.AppOutputStream.write(AppOutputStream.java:67)
        at java.base/sun.security.ssl.AppOutputStream.write(AppOutputStream.java:81)
        at SSLPoke.main(SSLPoke.java:31)
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at java.base/sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
        at java.base/sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
        at java.base/java.security.cert.CertPathBuilder.build(CertPathBuilder.java:297)
        at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
        ... 18 more

Found a lot on the net how to add special certs to java but i think in my java installation something is wrong in general.

So my question is what could cause such a thing???

Body:
Ended up installing oracle jdk 10 (also 10.0.2) and that works

C:\Users\Alexander\Downloads>java "SSLPoke" google.de 443
Successfully connected


问:
Is there any reason to use string.Format() with just a string parameter?
I'm currently updating some old code at work. I ran into a number of lines where string.Format() is used for seemingly no reason. I'm wondering if there is some use for using string.Format() without additional parameters, but I can't think of any.

What's the difference between this:

string query = String.Format(@"select type_cd, type_shpmt from codes");
```

<p>and this:</p>

<pre class="lang-cs prettyprint-override"><code>string query = "select type_cd, type_shpmt from codes";
</code>```

I also don't think that the @ is needed since it doesn't need to be a string literal, and it's not a multi-line string.

答:
While Format should be deleted, spare @ and make query being more readable:

```<code>  string query =
     @"select type_cd,
              type_shpmt
         from codes";
</code>```

If you want to modify table, field names etc. (which you can't do via Sql Parameters) try using string interpolation:

```<code>  string myTableName = "codes";

  ...

  string query =
     $@"select type_cd,
               type_shpmt
          from {myTableName}";
</code>```

Body:
I'm currently updating some old code at work. I ran into a number of lines where string.Format() is used for seemingly no reason. I'm wondering if there is some use for using string.Format() without additional parameters, but I can't think of any.

What's the difference between this:

string query = String.Format(@"select type_cd, type_shpmt from codes");

and this:

string query = "select type_cd, type_shpmt from codes";

I also don't think that the @ is needed since it doesn't need to be a string literal, and it's not a multi-line string.

Body:
While Format should be deleted, spare @ and make query being more readable:

  string query =
     @"select type_cd,
              type_shpmt
         from codes";

If you want to modify table, field names etc. (which you can't do via Sql Parameters) try using string interpolation:

  string myTableName = "codes";

  ...

  string query =
     $@"select type_cd,
               type_shpmt
          from {myTableName}";


问:
Check whether username is already in database
I am creating a help desk where one can create a new account. If the username is already in the database, you should get a message that tells you to take another username.
If the username is correct, the password must be provided with a hash before the data is entered in the database.

I have already searched for an answer via the internet but I don't find anything that works in my program.

//Declaratie private variabelen
        private int _klantnummer;
        private string _gebruikersnaam, _voornaam, _achternaam, _straatEnNummer, _postcode, _gemeente, _telefoonnummer, _email, _wachtwoord;
        private bool _admin;

        //Publieke eigenschappen
        private int Klantnummer
        {
            get { return _klantnummer; }
            set { _klantnummer = value; }
        }

        public string Gebruikersnaam
        {
            get { return _gebruikersnaam; }
            set { _gebruikersnaam = value; }
        }

        public string Voornaam
        {
            get { return _voornaam; }
            set { _voornaam = value; }
        }

        public string Achternaam
        {
            get { return _achternaam; }
            set { _achternaam = value; }
        }

        public string StraatEnNummer
        {
            get { return _straatEnNummer; }
            set { _straatEnNummer = value; }
        }

        public string Postcode
        {
            get { return _postcode; }
            set { _postcode = value; }
        }

        public string Gemeente
        {
            get { return _gemeente; }
            set { _gemeente = value; }
        }

        public string Telefoonnummer
        {
            get { return _telefoonnummer; }
            set { _telefoonnummer = value; }
        }

        public string Email
        {
            get { return _email; }
            set { _email = value; }
        }

        public string Wachtwoord
        {
            get { return _wachtwoord; }
            set { _wachtwoord = value; }
        }

        public bool Admin
        {
            get { return _admin; }
            set { _admin = value; }
        }

        //Default Constructor
        public Klant()
        {
            Klantnummer = 0;
            Gebruikersnaam = "";
            Voornaam = "";
            Achternaam = "";
            StraatEnNummer = "";
            Postcode = "";
            Gemeente = "";
            Telefoonnummer = "";
            Email = "";
            Wachtwoord = "";
            Admin = false;
        }

        //Constructor met parameters
        public Klant (string pGebruikersnaam, string pVoornaam, string pAchternaam, string pStraatEnNummer,
            string pPostcode, string pGemeente, string pTelefoonnummer, string pEmail, string pWachtwoord,
            bool pAdmin)
        {
            this.Gebruikersnaam = pGebruikersnaam;
            this.Voornaam = pVoornaam;
            this.Achternaam = pAchternaam;
            this.StraatEnNummer = pStraatEnNummer;
            this.Postcode = pPostcode;
            this.Gemeente = pGemeente;
            this.Telefoonnummer = pTelefoonnummer;
            this.Email = pEmail;
            this.Wachtwoord = pWachtwoord;
            this.Admin = pAdmin;
        }

        //Constructor met parameters met klantnummer
        public Klant(int pKlantnummer, string pGebruikersnaam, string pVoornaam, string pAchternaam, string pStraatEnNummer,
            string pPostcode, string pGemeente, string pTelefoonnummer, string pEmail, string pWachtwoord,
            bool pAdmin)
        {
            this.Klantnummer = pKlantnummer;
            this.Gebruikersnaam = pGebruikersnaam;
            this.Voornaam = pVoornaam;
            this.Achternaam = pAchternaam;
            this.StraatEnNummer = pStraatEnNummer;
            this.Postcode = pPostcode;
            this.Gemeente = pGemeente;
            this.Telefoonnummer = pTelefoonnummer;
            this.Email = pEmail;
            this.Wachtwoord = pWachtwoord;
            this.Admin = pAdmin;
        }

```

答: What I usually do is make the username field unique in the database then use a try...catch on the call to the database. If it fails for a unique validation error I know the username was already used and respond to the user.</p>


问:
Error inflating class androidx.constraintlayout.widget.ConstraintLayout when run in genymotion device
When i run my app in genymotion virtual device occur error and my app crashed.Error is:

```<code>5-31 13:15:18.838 1205-1205/com.mypackage E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mypackage/com.mypackage.StarterActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class androidx.constraintlayout.widget.ConstraintLayout
</code>```

My app gradle dependency:

```<code> implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
    implementation 'com.google.android.material:material:1.0.0-beta01'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0-beta01'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
    implementation 'androidx.recyclerview:recyclerview:1.0.0-rc02'
    implementation 'androidx.viewpager:viewpager:1.0.0'
    implementation 'com.intuit.sdp:sdp-android:1.0.6'
</code>```

Note: My app work fine on real device.

答:
Make sure constraint layout is updated to latest version:

```<code>implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
</code>```

And replace your xml tag names

```<code><androidx.constraintlayout.ConstraintLayout>
</code>```

with

```<code><androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Body:
When i run my app in genymotion virtual device occur error and my app crashed.Error is:

5-31 13:15:18.838 1205-1205/com.mypackage E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mypackage/com.mypackage.StarterActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class androidx.constraintlayout.widget.ConstraintLayout

My app gradle dependency:

 implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
    implementation 'com.google.android.material:material:1.0.0-beta01'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0-beta01'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
    implementation 'androidx.recyclerview:recyclerview:1.0.0-rc02'
    implementation 'androidx.viewpager:viewpager:1.0.0'
    implementation 'com.intuit.sdp:sdp-android:1.0.6'

Note: My app work fine on real device.

Body:
Make sure constraint layout is updated to latest version:

implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

And replace your xml tag names

<androidx.constraintlayout.ConstraintLayout>

with

<androidx.constraintlayout.widget.ConstraintLayout>


问:
what does this mean x86 assembly code mean?
I have come upon x86 assembly code I don't understand and can't find anything about it. The bit of code i don't understand is parentheses around register ecx: movb (%ecx),%al. What does this code mean? I am familiar with registers and instructions, but have never come upon this.

I was trying to find something about it in videos and guides, but did not find anything.

Looks something like this in context

```<code>pushl %ebp
movl %esp,%ebp
movl 8(%ebp),%ecx
...
movb (%ecx),%al  #<-- the code i am wondering about
</code>```

答:
The syntax (%reg) is the AT&T assembler syntax for dereferencing the content of a register as an address. It's equivalent to the Intel syntax [reg].

What you have there is the value in the partial register %al being written into the byte pointed to by the address in %ecx.

Body:
I have come upon x86 assembly code I don't understand and can't find anything about it. The bit of code i don't understand is parentheses around register ecx: movb (%ecx),%al. What does this code mean? I am familiar with registers and instructions, but have never come upon this.

I was trying to find something about it in videos and guides, but did not find anything.

Looks something like this in context

pushl %ebp
movl %esp,%ebp
movl 8(%ebp),%ecx
...
movb (%ecx),%al  #<-- the code i am wondering about


问:
How to store two dimension array of string in Elixir Ecto. How to put matching length to list?
How do I save 2d lists into postgres?
Or put matching lengths to lists?

I tried this in my migration..

```<code>  add :checkpoints, {:array, :string}
</code>```

and schema..

```<code>  field :checkpoints, {:array, {:array, :string}}
</code>```

But when i save this sample value of [["C23", "E12"], ["N34"], ["G22"]] to :checkpoints field,
I get this error:

```<code>(ArgumentError) nested lists must have lists with matching lengths
</code>```

答: All of our lists need to have the same length. Your first list has three elements, the other ones have only 1.</p>

Body:
How do I save 2d lists into postgres?
Or put matching lengths to lists?

I tried this in my migration..

  add :checkpoints, {:array, :string}

and schema..

  field :checkpoints, {:array, {:array, :string}}

But when i save this sample value of [["C23", "E12"], ["N34"], ["G22"]] to :checkpoints field,
I get this error:

(ArgumentError) nested lists must have lists with matching lengths


问:
Creating a windows shortcut (.lnk) to TortoiseHG's Repository Explorer
Is it possible to create a shortcut (a link, an icon on the Desktop) to one of my repositorie's Repository Explorer(TortoiseHG)? I don't like to navigate all the time to the folder and right click -> repository Explorer, i'm looking for a faster method, using a shortcut that can be accessed from anywhere.</p>

答:
for 1.X, one option is to create a shortcut using the -R switch to specify the repository directory:

```<code>hgtk.exe -R <repopath> log
</code>```

Another option is put a shortcut to your repository directory on your desktop, then right-click it and select "Hg Repository Explorer".

Body:
for 1.X, one option is to create a shortcut using the -R switch to specify the repository directory:

hgtk.exe -R <repopath> log

Another option is put a shortcut to your repository directory on your desktop, then right-click it and select "Hg Repository Explorer".


问:
Is there a difference between the statements below?
I was looking at the solution for the Titanic Problem in Kaggle and there is a part that it does:

```<code>data['Cabin'] = data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M')
</code>```

What is the difference between the code above and only:

```<code>data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M')
</code>```

答:
data['Cabin'] = data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M') replaces your 'Cabin' column with a transformed one.

data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M') returns you a new Series object (in your case it is a column, I suppose).

So if you will write it the second way, your original dataframe will not change. If you will write it the first way, it will change.

.replace() has an attribute inplace. It is set to False by default. If you will set it to True, the behaviour of data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M', inplace=True) will be equal to data['Cabin'] = data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M')

Body:
I was looking at the solution for the Titanic Problem in Kaggle and there is a part that it does:

data['Cabin'] = data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M')

What is the difference between the code above and only:

data['Cabin'].replace(['A', 'D', 'E', 'T'], 'M')


问:
What azure background process should I use?
So I am getting confused with what is the right approach to implementing code that fires on a scheduled bases within azure.

Originally we were using a standard console app that would be put in the webjob folder on deployment. I found this a bit noddy as we had logic looping and waiting for the right time to fire.

I then tried the azure webjob package https://github.com/Azure/azure-webjobs-sdk-extensions, but see this has gone quiet and the master branch is currently broken! I like because it has a CRON type approach with a function.cs, but now not sure if this is being maintained.

So do people have a preference on how a background process would run, e.g. a scheduled task that would run at 2am every day against a database?

Too much choice and not enough consensus on what the right way is?

Much appreciated in advance

答:
I can think of three options, all of which are valid and can suit your needs. Which one to choose in the end comes down to your requirement specifics and your technical expertise.

WebJobs. These are the most powerful and most difficult to build and maintain. You typically use a dedicated project template in Visual Studio to author these. You can ignore that GitHub link - that's not what you need. Make sure you have the Azure workload enabled in Visual Studio and create a WebJob project.

Azure Functions. These are a more lightweight alternative to WebJobs. There is Visual Studio tooling available for this as well but you also have the option of writing your code directly in the portal. Azure Functions will time out after some period of time, so if your job runs more more than a minute or two this might not be the best option.

Logic Apps. This is more of a power user tool with an easy to use (debatable) designer interface. But it's also incredibly powerful and you can call WebJobs or Functions if you need to from a Logic App.

I could add links but I'm sure you could find them easily enough.


问:
How to get path to dependency jar with maven
Given a simple Maven project with for example JUnit as dependency, how do I get the full filepath to the junit.jar inside the local maven repository it will be installed into?!

e.g. How to get from artifact junit:junit to /Users/foobar/.m2/repository/junit/junit/4.11/junit-4.11.jar?

答:
The maven dependency plugin has a goal 'properties'. From documentation:

Goal that sets a property pointing to the artifact file for each project dependency. For each dependency (direct and transitive) a project property will be set which follows the groupId:artifactId:type:[classifier] form and contains the path to the resolved artifact.

So something like this should do the trick:

```<code><properties>
    <maven-dependency-plugin.version>3.1.1</maven-dependency-plugin.version>
</properties>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>${maven-dependency-plugin.version}</version>
    <executions>
        <execution>
            <phase>initialize</phase>
            <goals>
                <goal>properties</goal>
            </goals>
        </execution>
    </executions>
</plugin>
</code>```

Then the property ${junit:junit:jar} should contain the jar file path

Body:
The maven dependency plugin has a goal 'properties'. From documentation:

Goal that sets a property pointing to the artifact file for each project dependency. For each dependency (direct and transitive) a project property will be set which follows the groupId:artifactId:type:[classifier] form and contains the path to the resolved artifact.

So something like this should do the trick:

<properties>
    <maven-dependency-plugin.version>3.1.1</maven-dependency-plugin.version>
</properties>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>${maven-dependency-plugin.version}</version>
    <executions>
        <execution>
            <phase>initialize</phase>
            <goals>
                <goal>properties</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Then the property ${junit:junit:jar} should contain the jar file path


问:
Request.Files is empty when files come through as an array
I'm doing some integration with a third party form builder software that allows the form to be posted to our own server. The form data and files are then saved to a DB. The issue is when the form contains multiple file upload fields, Request.Files is always empty.

Using Fiddler, I can see the binary files coming through. The only thing that I can think of is that the field name contains brackets in them (because it's being sent as an array) and so the model binder can't bind it properly? The field names that are coming through are tfa_20[0] and tfa_20[1].

Code-wise, it's pretty standard stuff:

```<code>var data = new Submission()
{
    ConfigurationDetailId = configDetail.Id,
    SubmitterEmail = submitterEmail,
    SubmissionData = Request.Form.AllKeys.Select(k => new SubmissionData()
    {
        FieldName = k,
        FieldValue = Request.Form[k]
    }).ToList(),
    SubmissionFiles = new List<SubmissionFile>()
};

// process any files uploaded
if (Request.Files.Count > 0)
{
    foreach (string field in Request.Files)
    {
        var uploadedFile = Request.Files[field];

        if (!string.IsNullOrEmpty(fileName))
        {
                data.SubmissionFiles.Add(GetSubmissionFile(uploadedFile, fileName));
        }
    }
}

Repository.SaveForm(data);
</code>```

Any help would greatly be appreciated.

答:
Use HttpPostedFileBase in order to get posted file to your action. in case of multiple files,should be used an HttpPostedFileBase[] array.

To Enable uploading in forms, is necessary to add enctype="multipart/form-data" to your form tag. or if you use razor syntax change your beginForm tag to this.

View.cshtml

```<code>   @using (Html.BeginForm("action","controller", FormMethod.Post, new { @enctype =
  "multipart/form-data" }))
    {
    }
</code>```

```<code> public ActionResult YourAction(HttpPostedFileBase[] files)
    {
        var data = new Submission()
        {
            ConfigurationDetailId = configDetail.Id,
            SubmitterEmail = submitterEmail,
            SubmissionData = Request.Form.AllKeys.Select(k => new SubmissionData()
            {
                FieldName = k,
                FieldValue = Request.Form[k]
            }).ToList(),
            SubmissionFiles = new List<SubmissionFile>()
        };

        if (files.Length > 0)
        {
            foreach (HttpPostedFileBase file in files)
            {
                var uploadedFile = file;

                if (!string.IsNullOrEmpty(file.FileName))
                {
                    data.SubmissionFiles.Add(GetSubmissionFile(uploadedFile, file.fileName));
                }
            }
        }

        return View();
    }
</code>```

Body:
I'm doing some integration with a third party form builder software that allows the form to be posted to our own server. The form data and files are then saved to a DB. The issue is when the form contains multiple file upload fields, Request.Files is always empty.

Using Fiddler, I can see the binary files coming through. The only thing that I can think of is that the field name contains brackets in them (because it's being sent as an array) and so the model binder can't bind it properly? The field names that are coming through are tfa_20[0] and tfa_20[1].

Code-wise, it's pretty standard stuff:

var data = new Submission()
{
    ConfigurationDetailId = configDetail.Id,
    SubmitterEmail = submitterEmail,
    SubmissionData = Request.Form.AllKeys.Select(k => new SubmissionData()
    {
        FieldName = k,
        FieldValue = Request.Form[k]
    }).ToList(),
    SubmissionFiles = new List<SubmissionFile>()
};

// process any files uploaded
if (Request.Files.Count > 0)
{
    foreach (string field in Request.Files)
    {
        var uploadedFile = Request.Files[field];

        if (!string.IsNullOrEmpty(fileName))
        {
                data.SubmissionFiles.Add(GetSubmissionFile(uploadedFile, fileName));
        }
    }
}

Repository.SaveForm(data);

Any help would greatly be appreciated.

Body:
Use HttpPostedFileBase in order to get posted file to your action. in case of multiple files,should be used an HttpPostedFileBase[] array.

To Enable uploading in forms, is necessary to add enctype="multipart/form-data" to your form tag. or if you use razor syntax change your beginForm tag to this.

View.cshtml

   @using (Html.BeginForm("action","controller", FormMethod.Post, new { @enctype =
  "multipart/form-data" }))
    {
    }

 public ActionResult YourAction(HttpPostedFileBase[] files)
    {
        var data = new Submission()
        {
            ConfigurationDetailId = configDetail.Id,
            SubmitterEmail = submitterEmail,
            SubmissionData = Request.Form.AllKeys.Select(k => new SubmissionData()
            {
                FieldName = k,
                FieldValue = Request.Form[k]
            }).ToList(),
            SubmissionFiles = new List<SubmissionFile>()
        };

        if (files.Length > 0)
        {
            foreach (HttpPostedFileBase file in files)
            {
                var uploadedFile = file;

                if (!string.IsNullOrEmpty(file.FileName))
                {
                    data.SubmissionFiles.Add(GetSubmissionFile(uploadedFile, file.fileName));
                }
            }
        }

        return View();
    }


问:
Find most significant DWORD in an DWORD array
I want to find the most significant DWORD which isn't equal to 0 in an DWORD array. The algorithm should be optimized for data sizes up to 128 byte.

I've made three different functions, which all returns the index of the specific DWORD.

```<code>unsigned long msb_msvc(long* dw, std::intptr_t n)
{
    while( --n )
    {
        if( dw[n] )
            break;
    }
    return n;
}

static inline unsigned long msb_386(long* dw, std::intptr_t n)
{
    __asm
    {
        mov ecx, [dw]
        mov eax, [n]

__loop: sub eax, 1
        jz  SHORT __exit
        cmp DWORD PTR [ecx + eax * 4], 0
        jz  SHORT __loop
__exit:
    }
}

static inline unsigned long msb_sse2(long* dw, std::intptr_t n)
{
    __asm
    {
        mov  ecx, [dw]
        mov  eax, [n]
        test ecx, 0x0f
        jnz  SHORT __128_unaligned

__128_aligned:
        cmp      eax, 4
        jb       SHORT __64
        sub      eax, 4
        movdqa   xmm0, XMMWORD PTR [ecx + eax * 4]
        pxor     xmm1, xmm1
        pcmpeqd  xmm0, xmm1
        pmovmskb edx, xmm0
        not      edx
        and      edx, 0xffff
        jz       SHORT __128_aligned
        jmp      SHORT __exit

__128_unaligned:
        cmp      eax, 4
        jb       SHORT __64
        sub      eax, 4
        movdqu   xmm0, XMMWORD PTR [ecx + eax * 4]
        pxor     xmm1, xmm1
        pcmpeqd  xmm0, xmm1
        pmovmskb edx, xmm0
        not      edx
        and      edx, 0xffff
        jz       SHORT __128_unaligned
        jmp      SHORT __exit

__64:
        cmp      eax, 2
        jb       __32
        sub      eax, 2
        movq     mm0, MMWORD PTR [ecx + eax * 4]
        pxor     mm1, mm1
        pcmpeqd  mm0, mm1
        pmovmskb edx, mm0
        not      edx
        and      edx, 0xff
        emms
        jz       SHORT __64
        jmp      SHORT __exit

__32:
        test eax, eax
        jz   SHORT __exit
        xor  eax, eax
        jmp  __leave ; retn

__exit:
        bsr      edx, edx
        shr      edx, 2
        add eax, edx

__leave:
    }
}
</code>```

These function should be used, to preselect data which will be compared against each other. So, it needs to be performant.

Does anybody know a better algorithm?

答: I think you are just looking for the first non-zero word in a given array. I would definitely go with a simple loop written in C. If there's some reason why this is super performance critical, I would recommend you look in the larger context of your program and ask e.g. the question why you need to find the non-zero object from the array and why can't you know its location already.

Body:
I want to find the most significant DWORD which isn't equal to 0 in an DWORD array. The algorithm should be optimized for data sizes up to 128 byte.

I've made three different functions, which all returns the index of the specific DWORD.

unsigned long msb_msvc(long* dw, std::intptr_t n)
{
    while( --n )
    {
        if( dw[n] )
            break;
    }
    return n;
}

static inline unsigned long msb_386(long* dw, std::intptr_t n)
{
    __asm
    {
        mov ecx, [dw]
        mov eax, [n]

__loop: sub eax, 1
        jz  SHORT __exit
        cmp DWORD PTR [ecx + eax * 4], 0
        jz  SHORT __loop
__exit:
    }
}

static inline unsigned long msb_sse2(long* dw, std::intptr_t n)
{
    __asm
    {
        mov  ecx, [dw]
        mov  eax, [n]
        test ecx, 0x0f
        jnz  SHORT __128_unaligned

__128_aligned:
        cmp      eax, 4
        jb       SHORT __64
        sub      eax, 4
        movdqa   xmm0, XMMWORD PTR [ecx + eax * 4]
        pxor     xmm1, xmm1
        pcmpeqd  xmm0, xmm1
        pmovmskb edx, xmm0
        not      edx
        and      edx, 0xffff
        jz       SHORT __128_aligned
        jmp      SHORT __exit

__128_unaligned:
        cmp      eax, 4
        jb       SHORT __64
        sub      eax, 4
        movdqu   xmm0, XMMWORD PTR [ecx + eax * 4]
        pxor     xmm1, xmm1
        pcmpeqd  xmm0, xmm1
        pmovmskb edx, xmm0
        not      edx
        and      edx, 0xffff
        jz       SHORT __128_unaligned
        jmp      SHORT __exit

__64:
        cmp      eax, 2
        jb       __32
        sub      eax, 2
        movq     mm0, MMWORD PTR [ecx + eax * 4]
        pxor     mm1, mm1
        pcmpeqd  mm0, mm1
        pmovmskb edx, mm0
        not      edx
        and      edx, 0xff
        emms
        jz       SHORT __64
        jmp      SHORT __exit

__32:
        test eax, eax
        jz   SHORT __exit
        xor  eax, eax
        jmp  __leave ; retn

__exit:
        bsr      edx, edx
        shr      edx, 2
        add eax, edx

__leave:
    }
}

These function should be used, to preselect data which will be compared against each other. So, it needs to be performant.

Does anybody know a better algorithm?


问:
NotifyDataSetChanged isn't updating arrayList when called the second time
Why is my question getting negative marks? i do not understand. Please help.

I have 5 lists displaying in the adapter one after another. I have to delete 2 rows when user clicks on a button in the activity. (Remove two options from the list every time the button is clicked) Each list gets the button click only once.
On click of button, NotifyDataSetChanged method does not update the list in the adapter.

For now it is happening for list 1, when 2nd list comes in, the button is clicked, 2 items from arraylist are deleted but notifyDataSetChanged does not update the list in the adapter.

In Activity :
row_number = count that i get from implementing the interface mentioned in adapter

```<code>  private void removeTwoFunctionality() {

    button_removeTwo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (row_number == 1) {
                TextArray1.remove(0);
                TextArray1.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
            if (row_number == 2) {
                TextArray2.remove(0);
                TextArray2.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
            if (row_number == 3) {
                TextArray3.remove(0);
                TextArray3.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
            if (row_number == 4) {
                TextArray4.remove(0);
                TextArray4.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
            if (row_number == 5) {
                TextArray5.remove(0);
                TextArray5.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
        }
    });
}
</code>```

In ADAPTER onBindViewHolder:
All the conditions are satisfied when next list arrives

```<code>// list 1
    if (!TextArray1.isEmpty()) {
        count = 1;
        holder.name.setText(TextArray1.get(position).getTitle());
    }
// list 2
    if (TextArray1.isEmpty() && TextArray2.size() > 0) {
        count = 2;
        holder.name.setText(TextArray2.get(position).getTitle());
    }
// list 3
    if (TextArray2.isEmpty() && TextArray3.size() > 0) {
        count = 3;
        holder.name.setText(TextArray3.get(position).getTitle());
    }
// list 4
    if (TextArray3.isEmpty() && TextArray4.size() > 0) {
        count = 4;
        holder.name.setText(TextArray4.get(position).getTitle());
    }
// list 5
    if (TextArray4.isEmpty() && TextArray5.size() > 0) {
        count = 5;
        holder.name.setText(TextArray5.get(position).getTitle());
    }
// interface to know the count in the activity
    if (mOnAnswerListener != null) {
        mOnAnswerListener.getRowNumber(count);
    }
</code>```

答:
Try like this </p>

```<code>                TextArray5.remove(0);
                TextArray5.remove(1);
                adapter.RemoveTwoButtonClicked();
                adapter.notifyDataSetChanged();
</code>```

Body:
Why is my question getting negative marks? i do not understand. Please help.

I have 5 lists displaying in the adapter one after another. I have to delete 2 rows when user clicks on a button in the activity. (Remove two options from the list every time the button is clicked) Each list gets the button click only once.
On click of button, NotifyDataSetChanged method does not update the list in the adapter.

For now it is happening for list 1, when 2nd list comes in, the button is clicked, 2 items from arraylist are deleted but notifyDataSetChanged does not update the list in the adapter.

In Activity :
row_number = count that i get from implementing the interface mentioned in adapter

  private void removeTwoFunctionality() {

    button_removeTwo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (row_number == 1) {
                TextArray1.remove(0);
                TextArray1.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
            if (row_number == 2) {
                TextArray2.remove(0);
                TextArray2.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
            if (row_number == 3) {
                TextArray3.remove(0);
                TextArray3.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
            if (row_number == 4) {
                TextArray4.remove(0);
                TextArray4.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
            if (row_number == 5) {
                TextArray5.remove(0);
                TextArray5.remove(1);
                adapter.notifyDataSetChanged();
                adapter.RemoveTwoButtonClicked();
            }
        }
    });
}

In ADAPTER onBindViewHolder:
All the conditions are satisfied when next list arrives

// list 1
    if (!TextArray1.isEmpty()) {
        count = 1;
        holder.name.setText(TextArray1.get(position).getTitle());
    }
// list 2
    if (TextArray1.isEmpty() && TextArray2.size() > 0) {
        count = 2;
        holder.name.setText(TextArray2.get(position).getTitle());
    }
// list 3
    if (TextArray2.isEmpty() && TextArray3.size() > 0) {
        count = 3;
        holder.name.setText(TextArray3.get(position).getTitle());
    }
// list 4
    if (TextArray3.isEmpty() && TextArray4.size() > 0) {
        count = 4;
        holder.name.setText(TextArray4.get(position).getTitle());
    }
// list 5
    if (TextArray4.isEmpty() && TextArray5.size() > 0) {
        count = 5;
        holder.name.setText(TextArray5.get(position).getTitle());
    }
// interface to know the count in the activity
    if (mOnAnswerListener != null) {
        mOnAnswerListener.getRowNumber(count);
    }

Body:
Try like this

                TextArray5.remove(0);
                TextArray5.remove(1);
                adapter.RemoveTwoButtonClicked();
                adapter.notifyDataSetChanged();


问:
Set label text to Bold on tap
I need to have the text of a cell turn bold when tapped then return to light when tapped again

I tried
self.preguntaLabel.font = UIFont.boldSystemFont(ofSize: 14.0)
and it works but it doesn't return to light weight.

So lets say

(This is the cell)

When tapped it has to turn the text bold

(This is the cell)

Then, when tapped again, return to light

(This is the cell)

答:
Override setSelected(_:,animated:) in custom UITableViewCell, i.e.

```<code>class CustomCell: UITableViewCell {
    @IBOutlet weak var preguntaLabel: UILabel!

    override func setSelected(_ selected: Bool, animated: Bool) {
        if selected {
            self.preguntaLabel.font = UIFont.systemFont(ofSize: 14.0, weight: .bold)
        } else {
            self.preguntaLabel.font = UIFont.systemFont(ofSize: 14.0)
        }
    }

    //Rest of the code...
}
</code>```

Title: Set label text to Bold on tap

Body:
Override setSelected(_:,animated:) in custom UITableViewCell, i.e.

class CustomCell: UITableViewCell {
    @IBOutlet weak var preguntaLabel: UILabel!

    override func setSelected(_ selected: Bool, animated: Bool) {
        if selected {
            self.preguntaLabel.font = UIFont.systemFont(ofSize: 14.0, weight: .bold)
        } else {
            self.preguntaLabel.font = UIFont.systemFont(ofSize: 14.0)
        }
    }

    //Rest of the code...
}


问:
Is there a possibility to serialize Kotlin Data class with function literal?
I have following setup:

Kotlin data class:

```<code>data class Error(val throwable: Throwable, val reloadAction: (() -> Unit)? = null) : Serializable
</code>```

Initialization of class:

```<code>val instance = Error(throwable,this::loadData)
</code>```

Where this is ViewModel from Android Architecture components

When I'm passing this data class to parcelable:

```<code>parcel.writeSerializable(instance as Serializable)
</code>```

I get following exception:

```<code>java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.mypackagename.Error)
        at android.os.Parcel.writeSerializable(Parcel.java:1468)
        at com.mypackagename.CustomView$Companion$SavedState.writeToParcel(CustomView.kt:177)
...
Caused by: java.io.NotSerializableException: com.mypackagename.ExampleViewModel
</code>```

In this question: Is there a way to pass a function reference between activities? is following answer:

It will actually be Serializable if it is a function reference (SomeClass::someFunction) or a lambda. But it might not be, if it is some custom implementation of the functional interface () -> Unit, so you should check that and handle the cases when it's not.

Is this my case? Or data class cannot be serialized when function is function of non serializable object (ViewModel)? Are there any other possibilities how to pass function literal as Serializable inside data class?

答: I had similar issue, my problem was that I didn't expect a data class not to be Serializable by default. It is important not to forget to implement the Serializable interface.

Body:
I have following setup:

Kotlin data class:

data class Error(val throwable: Throwable, val reloadAction: (() -> Unit)? = null) : Serializable

Initialization of class:

val instance = Error(throwable,this::loadData)

Where this is ViewModel from Android Architecture components

When I'm passing this data class to parcelable:

parcel.writeSerializable(instance as Serializable)

I get following exception:

java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.mypackagename.Error)
        at android.os.Parcel.writeSerializable(Parcel.java:1468)
        at com.mypackagename.CustomView$Companion$SavedState.writeToParcel(CustomView.kt:177)
...
Caused by: java.io.NotSerializableException: com.mypackagename.ExampleViewModel

In this question: Is there a way to pass a function reference between activities? is following answer:

It will actually be Serializable if it is a function reference (SomeClass::someFunction) or a lambda. But it might not be, if it is some custom implementation of the functional interface () -> Unit, so you should check that and handle the cases when it's not.

Is this my case? Or data class cannot be serialized when function is function of non serializable object (ViewModel)? Are there any other possibilities how to pass function literal as Serializable inside data class?


问:
Working with Sets of Self-Tracking Entities causing performance issues
I saw this Post by ADO.Net team which looks very promising until I started using it in my application. I have EF 4.0 model with close to 100 self tracking entities. After including the iterator in my project, any of the extension methods "StartTrackingAll" or "StopTrackingAll" would take 5sec to finish. Has anyone ran into same issue or anyone knows of any better option.</p>

答:
Are your entities in relation? In that case you don't need to use StartTrackingAll because StartTracking itself starts tracking for whole object graph:

The StartTracking method instructs the
  change tracker on the entity to start
  recording any changes applied to the
  entity. This includes changes to
  scalar properties, collections, and
  references to other entities. The
  self-tracking entities start tracking
  automatically when they are
  deserialized into the client through
  the Windows Communication Foundation
  (WCF). The tracking is also turned on
  for newly created entities in the
  following scenarios:

```<code>* A relationship is created between the new entity and an entity that is already tracking changes.

* The MarkAs[State] or AcceptChanges method is called on an entity.
</code>```

If you are not using related entities it sounds strange that you need to track 100 entities in the same time. Also if entities don't have relations it is perhaps not needed to track them at all.

Body:
Are your entities in relation? In that case you don't need to use StartTrackingAll because StartTracking itself starts tracking for whole object graph:

The StartTracking method instructs the
  change tracker on the entity to start
  recording any changes applied to the
  entity. This includes changes to
  scalar properties, collections, and
  references to other entities. The
  self-tracking entities start tracking
  automatically when they are
  deserialized into the client through
  the Windows Communication Foundation
  (WCF). The tracking is also turned on
  for newly created entities in the
  following scenarios:

* A relationship is created between the new entity and an entity that is already tracking changes.

* The MarkAs[State] or AcceptChanges method is called on an entity.

If you are not using related entities it sounds strange that you need to track 100 entities in the same time. Also if entities don't have relations it is perhaps not needed to track them at all.