Skip to content
Advertisement

Spring boot Bean annotation and instance variable flow in Configuration

I am new to the spring boot framework and I have some confusion regarding the @Bean annotation and how the instance variable gets changed by the Bean. I have a below example and if someone can answer my questions will be really helpful:

  1. If I am defining restTemplate in my instance variable will userRestTemplate template bean will be able to change its value?
  2. If userRestTemplate is changing its value then userDetail will have the updated value by userRestTemplate bean?
  3. If not what will be userdetail bean will be setting in setTemplate method?
JavaScript

Advertisement

Answer

Actually, I don’t think this is the standard way of creation.

As when you annotate the method with @Bean, you mean you want to ask Spring to help you to manage the bean. Therefore it makes no sense to store the bean instance by yourself as a local variable.

Instead of storing the instance in the class field, you should ask Spring to give you the instance instead.

There are multiple ways to do that.

  1. Specify RestTemplate as a parameter in @Bean method. In case you have asked Spring to manage multiple RestTemplate instance, which is possible. Then you should specify the parameter name same as @Named which is userRestTemplate, so that Spring can find the correct restTemplate properly.
JavaScript
  1. Use @Autowired Annotation.
JavaScript

The advantage of asking Spring to manage java beans, instead of managing by ourselves. You would have the advantage to use Spring AOP, …

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement