zero01alpha zero01alpha - 12 days ago 6
Java Question

Does Spring automatically Autowire constructor args in java bean definitions?

Let's say I have the following bean definitions

@Bean
public Beehive beehive(ArrayList<Bee> bees) {
return new Beehive(bees);
}

@Bean
public ArrayList<Bee> bees() {
return new ArrayList<Bee>();
}


Would the
bees
in the
beehive
bean method be Autowired in?

I am asking because I have an application that is behaving like this without using the
@Autowired
annotation, and want be make sure I understand what's going on.

Answer

Does Spring automatically Autowire constructor args in java bean definitions?

Yes, it does. You can refer here from the Spring doc which I have added below (emphasis mine).

A @Bean annotated method can have an arbitrary number of parameters describing the dependencies required to build that bean. For instance if our TransferService requires an AccountRepository we can materialize that dependency via a method parameter:

@Configuration 
public class AppConfig {
    @Bean
    public TransferService transferService(AccountRepository accountRepository) {
        return new TransferServiceImpl(accountRepository);
    }
}

The resolution mechanism is pretty much identical to constructor-based dependency injection.

Comments