Home > Enterprise >  Bean creation with parameters SpringBoot
Bean creation with parameters SpringBoot

Time:10-22

For Bean creation in SpringBoot, we use class annotated with the @Component with some bean creation methods annotated with @Bean annotation. Now, I have always been using @Bean like this:

@Bean
public func getSome() {
    return someFunc(param1, param2, param3);
}

Now, what I saw in some code is this:

@Bean
public func getSome(Type1 param1, Type2 param2, Type 3 param3) {
    return someFunc(param1, param2, param3);
}

So basically, Beans are created when the SpringBoot context loads. What I am confused here is how will SpringBoot pick up the parameters in the bean (the second example) .

Can someone please help me understand this ?

PS: Please let me know if the question is not clear. :)

CodePudding user response:

Spring will do standard lookup for Type1, Type2, Type3 types beans in the context. If those are not found, Spring will try to create new instances using default constructor. If no default constructor, startup will fail.

Probably there are some more mechanics, but basics is this.

CodePudding user response:

@Bean is similar to the Spring stereotypes (@Component, @Service, @Controller, @RestController, @Repository, and @Configuration).

When you write a method with @Bean on top of it, it is similar to using one of the stereotypes on top of a class with a constructor (with @Autowired), so its dependencies can be injected via the constructor by Spring; therefore, those parameters must be Spring beans so that they can be injected into your @Bean annotated method.

The way spring understands the injection order is via a dependency graph that Spring creates and starts creating beans from classes that either have no dependencies or their dependencies have been created and are ready to be injected.

  • Related