Marcin Kapusta
Marcin Kapusta

Reputation: 5396

Autowiring Bean before initialization of another Bean

Spring question.

I have two questions related to spring.

If I declare bean like this:

@Service
public class Downloader {
    @Bean
    public String bean1() {
        return "bean1";
    }
}

Then if other classes will be autowiring "bean1" then method bean1 will be called several times? Or one instance of bean1 will be created and reused?

Second question. How to Autowire some other bean e.g. "bean2" which is String "externalBean" that can be used to construct bean1.

@Service
public class Downloader {

    @Autowire
    private String bean2;       

    @Bean
    public String bean1() {
        return "bean1" + this.bean2;
    }
}

Currently I'm trying to Autowire this bean2 but it is null during bean1 call. Is there any mechanism that I can specify order of this. I don't know in what context looking for this kind of info in Spring docs.

Upvotes: 0

Views: 676

Answers (2)

LppEdd
LppEdd

Reputation: 21154

Then if other classes will be autowiring "bean1" then method bean1 will be called several times? Or one instance of bean1 will be created and reused?

There will be only a single instance of bean1, as the implicit scope is Singleton (no @Scope annotation present).

Second question. How to Autowire some other bean e.g. "bean2" which is String "externalBean" that can be used to construct bean1.

Being that it is a String, a @Qualifier might be required

@Bean
@Qualifier("bean2")
public String bean2() {
    return "bean2";
}

Then

@Bean
public String bean1(@Qualifier("bean2") final String bean2) {
    return "bean1" + bean2;
}

However, this works too.
Spring will be able to look at the name of the Bean and compare it to the parameter's one.

@Bean
public String bean2() {
    return "bean2";
}

and

@Bean
public String bean1(final String bean2) {
    return "bean1" + bean2;
}

The order is calculated automatically by Spring, based on a Bean dependencies.

Upvotes: 1

Maciej Kowalski
Maciej Kowalski

Reputation: 26552

Just simple @Bean annotation used sets the scope to standard singleton, so there will be only one created. According to the docs if you want to change you need to explicitly add another annotation:

@Scope changes the bean's scope from singleton to the specified scope

Upvotes: 1

Related Questions