Spring autowire =“ byType”与Java Config吗?

时间:2018-11-20 19:11:56

标签: spring spring-framework-beans

我可以按以下方式在XML配置中按类型和名称自动接线

<bean name="employee1" class="com.Class1" autowire="byName">
<bean name="employee2" class="com.Class2" autowire="byType">

但是如何在Java配置中完成相同的操作?我的意思是,什么等同于autoconfig =“ byName”和byautowire =“ byType”属性的Java Config?

@Configuration
public class JavaConfig {

//How to configure beans here, like above?

}

以下代码不起作用

    @Bean
    public Company company(){
return new Company();
    }

    @Bean
    public Employee employee1(@Autowired Company company){
return new Employee();
    }

谢谢!

1 个答案:

答案 0 :(得分:0)

当您仅通过@Autowired注释自动接线时-表示按类型自动接线。

如果要按名称自动布线,则需要同时使用@Autowired@Qualifier注释。

示例:

@Configuration
public class JavaConfig {

    @Bean
    @Qualifier("stackoverflow")
    public Company company(){
    }

    @Bean
    public Employee employee1(@Autowired Company company){
    }

    @Bean
    public Employee employee2(@Autowired @Qualifier("stackoverflow") Company company){
    }

}

已更新:您还可以使用@Bean批注的参数:

@Bean
public Company company(){
    return new Company();
}

@Bean(autowire = Autowire.BY_NAME)
public Employee employee1(@Autowired Company company){
    return new Employee();
}

请参阅其他信息here