0

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.

Marcin Kapusta
  • 5,076
  • 3
  • 38
  • 55
  • 2
    See https://stackoverflow.com/questions/7868335/spring-make-sure-a-particular-bean-gets-initialized-first – Ori Marko Apr 02 '19 at 13:26
  • Check out https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factory-scopes for information on _when_ new beans are instantiated. – Not a JD Apr 02 '19 at 13:30

2 Answers2

1

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

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
1

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.

LppEdd
  • 20,274
  • 11
  • 84
  • 139