title: Calling a @Bean annotated method in Spring java configuration
body: <p>I'm curious about how spring injection handles calling methods with the <code>@Bean</code> annotation. If I put a <code>@Bean</code> annotation on a method, and return an instance, I understand that that tells spring to create a bean by calling the method and getting the returned instance. However, sometimes that bean has to be used to wire other beans or setup other code. The usual way this is done is to call the <code>@Bean</code> annotated method to get an instance. My question is, why doesn't this cause there to be multiple instances of the bean floating around?</p>
  
  <p>For example, see the code below (taken from another question). The <code>entryPoint()</code> method is annotated with <code>@Bean</code>, so I would imagine spring will create a new instance of <code>BasicAuthenticationEntryPoint</code> as a bean. Then, we call <code>entryPoint()</code> again in the configure block, but it seems like <code>entryPoint()</code> returns the bean instance, and isn't called multiple times (I tried logging, and only got one log entry). Potentially we could call <code>entryPoint()</code> multiple times in other parts of the configuration, and we would always get the same instance. Is my understanding of this correct? Does spring do some magical rewriting of methods annotated with <code>@Bean</code>?</p>
  
  <pre><code>@Bean
  public BasicAuthenticationEntryPoint entryPoint() {
      BasicAuthenticationEntryPoint basicAuthEntryPoint = new BasicAuthenticationEntryPoint();
      basicAuthEntryPoint.setRealmName("My Realm");
      return basicAuthEntryPoint;
  }
  
  @Override
  protected void configure(HttpSecurity http) throws Exception {
  
      http
          .exceptionHandling()
              .authenticationEntryPoint(entryPoint())
              .and()
          .authorizeUrls()
              .anyRequest().authenticated()
              .and()
          .httpBasic();       
  }
  </code></pre>