2014-12-19 4 views
1

Я создал приложение SpringBatch с конфигурацией java. У меня есть основной метод и класс, который представляет работу.Spring Batch с конфигурацией java

@ComponentScan 
@EnableAutoConfiguration 
public class App 
{ 
    public static void main(String[] args) 
    { 
     System.out.println("Starting Spring Batch Execution -------"); 
     SpringApplication.run(App.class, args);   
    } 
} 


@Configuration 
@EnableBatchProcessing 
public class FlatFileJob { 

    @Autowired 
    private JobBuilderFactory jobs; 

    @Autowired 
    private StepBuilderFactory steps; 

    /** 
    * Create and configure job 
    * @return 
    */ 
    @Bean(name = "Read RabbitMQ") 
    public Job addFlatFileJob(){ 
     return jobs.get("carJob") 
       .start(this.flatFileStep()) 
       .build(); 
    } 

    /** 
    * Create and configure the only step 
    * @return 
    */ 
    @Bean 
    public Step flatFileStep(){ 
     return steps.get("step") 
       .<Car, Car> chunk(3) 
       .reader(new CarItemReader()) 
       .processor(new CarItemProcessor()) 
       .writer(new CarItemWriter()) 
       .build(); 
    } 

    @Bean 
    public PlatformTransactionManager transactionManager(){ 
     return new ResourcelessTransactionManager(); 
    } 

    @Bean 
    public JobRepository jobRepository() throws Exception{ 
     JobRepository jobRepository = (JobRepository) new JobRepositoryFactoryBean(); 
     return jobRepository; 
    } 

    @Bean 
    public JdbcTemplate jdbcTemplate(DataSource dataSource){ 
     return new JdbcTemplate(dataSource); 
    } 

    @Bean 
    public DataSource getDataSource(){ 
     BasicDataSource dataSource = new BasicDataSource(); 
     dataSource.setDriverClassName("org.postgresql.Driver"); 
     dataSource.setUrl("jdbc:postgresql://127.0.0.1:5432/spring_batch"); 
     dataSource.setUsername("xxx"); 
     dataSource.setPassword("xxx"); 
     return dataSource; 
    } 
} 

Проблема заключается в том, что при выполнении приложения выдается исключение. Любая идея в чем проблема?

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flatFileJob': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.batch.core.configuration.annotation.JobBuilderFactory neoway.com.job.FlatFileJob.jobs; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobBuilders' defined in class path resource [org/springframework/batch/core/configuration/annotation/SimpleBatchConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.batch.core.configuration.annotation.JobBuilderFactory org.springframework.batch.core.configuration.annotation.AbstractBatchConfiguration.jobBuilders() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository' defined in class path resource [neoway/com/job/FlatFileJob.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.batch.core.repository.JobRepository neoway.com.job.FlatFileJob.jobRepository() throws java.lang.Exception] threw exception; nested exception is java.lang.ClassCastException: org.springframework.batch.core.repository.support.JobRepositoryFactoryBean cannot be cast to org.springframework.batch.core.repository.JobRepository 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:301) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706) 
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762) 
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482) 
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691) 
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320) 
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:952) 
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:941) 
    at neoway.com.App.main(App.java:50) 
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.batch.core.configuration.annotation.JobBuilderFactory neoway.com.job.FlatFileJob.jobs; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobBuilders' defined in class path resource [org/springframework/batch/core/configuration/annotation/SimpleBatchConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.batch.core.configuration.annotation.JobBuilderFactory org.springframework.batch.core.configuration.annotation.AbstractBatchConfiguration.jobBuilders() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository' defined in class path resource [neoway/com/job/FlatFileJob.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.batch.core.repository.JobRepository neoway.com.job.FlatFileJob.jobRepository() throws java.lang.Exception] threw exception; nested exception is java.lang.ClassCastException: org.springframework.batch.core.repository.support.JobRepositoryFactoryBean cannot be cast to org.springframework.batch.core.repository.JobRepository 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:522) 
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:298) 
    ... 15 common frames omitted 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobBuilders' defined in class path resource [org/springframework/batch/core/configuration/annotation/SimpleBatchConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.batch.core.configuration.annotation.JobBuilderFactory org.springframework.batch.core.configuration.annotation.AbstractBatchConfiguration.jobBuilders() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository' defined in class path resource [neoway/com/job/FlatFileJob.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.batch.core.repository.JobRepository neoway.com.job.FlatFileJob.jobRepository() throws java.lang.Exception] threw exception; nested exception is java.lang.ClassCastException: org.springframework.batch.core.repository.support.JobRepositoryFactoryBean cannot be cast to org.springframework.batch.core.repository.JobRepository 
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1095) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:990) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1021) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:964) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:862) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:494) 
    ... 17 common frames omitted 
+0

вы уверены, что вы можете иметь пробелы внутри имен фасоли весной? «Прочитайте RabbitMQ» – Abe

ответ

2

Ключ этот исключение org.springframework.batch.core.repository.support.JobRepositoryFactoryBean cannot be cast to org.springframework.batch.core.repository.JobRepository.

Линия с исключением: JobRepository jobRepository = (JobRepository) new JobRepositoryFactoryBean();.

Попытки переписать так: JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean()

+1

Спасибо человеку. Теперь я получил другое исключение. Настроить Spring Batch с java трудно для меня. Вы знаете какой-либо сайт или книгу, которые объясняют это? Официальное руководство не очень хорошо, и я не нашел хороших объяснений в Интернете. – HenioJR

+2

Есть много книг и сайтов на эту тему. Например, http://www.mkyong.com/tutorials/spring-batch-tutorial/, из моей практики он часто имеет хорошее объяснение различных тем с примерами примеров. Из книг, может быть, «Весенняя партия в действии» будет полезна. Я не уверен, что помогу тебе, но, возможно. –

0
@Bean 
public JobRepository jobRepository() throws Exception { 
    JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); 
    factory.setTransactionManager(transactionManager()); 
    factory.setIsolationLevelForCreate("ISOLATION_REPEATABLE_READ"); 
    factory.setDataSource(dataSource()); 
    factory.setDatabaseType("SQLSERVER"); 
    return factory.getObject(); 
} 

GetObject является удобным методом для литья JobRepositoryFactoryBean в JobRepository

1

Использованием Spring бутса проще всего будет иметь свой класс конфигурации продлить org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer, который конфигурирует JobRepository для вас с настройкой по умолчанию. Он использует источник данных, который используется в вашем приложении. Если он не может найти источник данных, он настроит a в памяти JobRepository.

Для справки использования ниже ссылка:
https://docs.spring.io/spring-batch/trunk/apidocs/org/springframework/batch/core/configuration/annotation/EnableBatchProcessing.html

Смежные вопросы