Spring autowire="byType" with Java Config?

1.1k Views Asked by At

I can autowire by type and by name in the XML config in the following manner

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

But how can I accomplish the same in Java config? I mean, what is Java Config equivalent of autowire="byName" and by autowire="byType" attributes?

@Configuration
public class JavaConfig {

//How to configure beans here, like above?

}

The following code is not working

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

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

Thanks in advance!

1

There are 1 best solutions below

2
On

When you just autowire via @Autowired annotation - it means autowiring by type.

If we want to autowire by name we need to use @Autowired and @Qualifier annotation together.

Example:

@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){
    }

}

Updated: Also you can use parameter of @Bean annotation:

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

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

Please see additional information here