简体   繁体   English

通过名称使用@ComponentScan进行Spring自动装配,但属性上不使用@Autowired

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

Just migrating from xml based config to java based config in Spring 4.3. 在Spring 4.3中只需从基于xml的配置迁移到基于Java的配置即可。

In xml we had 在xml中,

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

On Java classes we have no @Autowired annotations on fields: 在Java类上,字段上没有@Autowired批注:

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

Previously in xml With the default-autowire="byName" autowiring worked pretty well. 以前在xml中使用default-autowire="byName"自动default-autowire="byName"效果很好。

Now when moving to JavaConfig I cannot find a way to enable the default autowire mechanism for component scanning. 现在,当迁移到JavaConfig时,我找不到能为组件扫描启用默认自动装配机制的方法。

With autowire by name the wiring works without a @Autowired annotation. 按名称使用autowire时,接线可以使用@Autowired注释。

With @Bean(autowire=BY_NAME) i can define a bean to autowire by name, but I would need that mechanism for component scanning. 使用@Bean(autowire = BY_NAME),我可以定义一个通过名称自动装配的bean,但是我需要该机制来进行组件扫描。 Not to define all beans with @Bean factory method. 不使用@Bean工厂方法定义所有bean。

Also I try not to add @Autowired annotations to all fields across all classes. 另外,我尽量不要在所有类的所有字段中添加@Autowired批注。 Thats just too much to change. 多数民众赞成在太多改变。

My question now is: How to tell component-scan to autowire found beans by name? 我现在的问题是:如何告诉组件扫描按名称自动装配找到的豆子?

I don't know if I understand what you want to do, but Spring supports @Qualifier and @Resource annotations: 我不知道我是否了解您要做什么,但是Spring支持@Qualifier@Resource批注:

@Resource takes a name attribute, and by default Spring interprets that value as the bean name to be injected. @Resource具有名称属性,默认情况下,Spring将该值解释为要注入的Bean名称。 In other words, it follows by-name semantics 换句话说,它遵循名称语义

One solution would be to update the bean definition with a BeanFactoryPostProcessor to mark all beans to autowire by name like: 一种解决方案是使用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);
      }
    });
  }
}

I am still curious if there is a setting in spring that can do this. 我仍然很好奇春季是否可以做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM