Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Spring automatically Autowire constructor args in java bean definitions?

Tags:

java

spring

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.

like image 338
secondbreakfast Avatar asked Jun 01 '26 08:06

secondbreakfast


1 Answers

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.

like image 104
developer Avatar answered Jun 02 '26 20:06

developer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!