簡體   English   中英

通過名稱使用@ComponentScan進行Spring自動裝配,但屬性上不使用@Autowired

[英]Spring autowire by name with @ComponentScan but without @Autowired on property

在Spring 4.3中只需從基於xml的配置遷移到基於Java的配置即可。

在xml中,

<beans ... default-autowire="byName">
  <component-scan .../>
  ...
</beans>

在Java類上,字段上沒有@Autowired批注:

@Component
public class MyService {
  private OtherService otherService;
  // +setters
  ....
}

以前在xml中使用default-autowire="byName"自動default-autowire="byName"效果很好。

現在,當遷移到JavaConfig時,我找不到能為組件掃描啟用默認自動裝配機制的方法。

按名稱使用autowire時,接線可以使用@Autowired注釋。

使用@Bean(autowire = BY_NAME),我可以定義一個通過名稱自動裝配的bean,但是我需要該機制來進行組件掃描。 不使用@Bean工廠方法定義所有bean。

另外,我盡量不要在所有類的所有字段中添加@Autowired批注。 多數民眾贊成在太多改變。

我現在的問題是:如何告訴組件掃描按名稱自動裝配找到的豆子?

我不知道我是否了解您要做什么,但是Spring支持@Qualifier@Resource批注:

@Resource具有名稱屬性,默認情況下,Spring將該值解釋為要注入的Bean名稱。 換句話說,它遵循名稱語義

一種解決方案是使用BeanFactoryPostProcessor更新Bean定義,以標記所有要按名稱自動裝配的Bean,例如:

public class AutowireScannedByNameBeanPostProcessor implements BeanFactoryPostProcessor {
  @Override
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    Arrays.stream(beanFactory.getBeanDefinitionNames()).forEach(name -> {
      BeanDefinition beanDefinition = beanFactory.getBeanDefinition(name);
      if (beanDefinition instanceof ScannedGenericBeanDefinition) {
        ((ScannedGenericBeanDefinition) beanDefinition).setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_NAME);
      }
    });
  }
}

我仍然很好奇春季是否可以做到這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM