使用Spring和Java Config bean避免重复

时间:2015-02-25 12:30:37

标签: java spring spring-java-config

我在A组中有以下豆子:

@Bean
public AsyncItemProcessor OneUploadAsyncItemProcessor() {
    // ...
    asyncItemProcessor.setDelegate(processor(OVERRIDDEN_BY_EXPRESSION, OVERRIDDEN_BY_EXPRESSION));
    // ...

    return asyncItemProcessor;
}

@Scope(value = "step", proxyMode = ScopedProxyMode.INTERFACES)
@Bean
public ItemProcessor<MyItem, MyItem> processor(@Value("#{jobParameters[pushMessage]}") String pushMessage, @Value("#{jobParameters[jobId]}") String jobId) {
    return new PushItemProcessor(pushMessage, jobId);
}

现在我在B组中有以下内容:

@Bean
public AsyncItemProcessor TwpUploadAsyncItemProcessor() {
    // ...
    asyncItemProcessor.setDelegate(processor(OVERRIDDEN_BY_EXPRESSION, OVERRIDDEN_BY_EXPRESSION));

    return asyncItemProcessor;
}

如何将Bean处理器(在A类上定义)注入B类而不重复它。

1 个答案:

答案 0 :(得分:0)

您只需要在课程B中“自动装配”它。类似的东西:

class B {
  @Autowire
  //@Qualifier(value = "OneUploadAsyncItemProcessor")
  [modifier] AsyncItemProcessor OneUploadAsyncItemProcessor;
}

我假设你不想 - 并因此从类TwpUploadAsyncItemProcessor删除bean B并从class {包含/ autowire(已定义)bean OneUploadAsyncItemProcessor {1}}。如果是,则不需要A注释。

另一方面,如果您想要自动装配@Qualifier而不删除OneUploadAsyncItemProcessor和/或定义another bean TwpUploadAsyncItemProcessor类型AsyncItemProcessor,您将需要@Qualifier注释。