title: In Spring javaconfig, how to initialize a @Bean which depends on a @Service
body: <p>I have converted a Spring 4.0-based project from xml to javaconfig.</p>
  
  <p>On initialization, one of my beans needs to access Hibernate to fetch some config-data from the DB, through a Spring @Service (<code>buildingService</code>). The bean initialization looks like this:</p>
  
  <pre><code>@Bean
  @DependsOn({ "transactionManager", "webSocketHandler", "buildingService" })
  Smarty smarty() {
      Smarty bean = new Smarty();
      bean.init(); // I also tried @Bean(initMethod = "init") with no difference
      return bean;
  }
  </code></pre>
  
  <p>The problem is that in <code>bean.init()</code>, the service is accessed, which fails with a <code>NullPointerException</code>.</p>
  
  <p>I added <code>buildingService</code> to <code>@DependsOn</code> but it did not help.</p>
  
  <p>Probably the <code>@Service</code>-annotated classes are processed after the <code>@Bean</code> !?</p>
  
  <p>Can I initialize the <code>@Service</code>-annotated class myself upfront?</p>
  
  <p><strong>Edit 1</strong></p>
  
  <p>Thanks so far for all the feedback !</p>
  
  <p>I need to add some details:</p>
  
  <p>buildingService is not a <code>@Bean</code>, it's, well, a <code>@Service</code> and looks like this:</p>
  
  <pre><code>@Service("buildingService")
  @Transactional
  public class BuildingService {
  
  ...
  
      public List&lt;Building&gt; getAll() {
          final Session session = sessionFactory.getCurrentSession();
          final Query query = session.createQuery("from Building order by name");
          return query.list();
      }
  
  ...
  
  }
  </code></pre>
  
  <p>Smarty is a Spring managed Bean, and initialized in an <code>@Configuration</code>-annotated class which is doing the initialization of the root-context.</p>
  
  <p>Smarty has a direct dependency on buildingService, like so:</p>
  
  <pre><code>@Resource(name = "buildingService")
  private BuildingService     buildingService;
  </code></pre>
  
  <p>I tried annotating <code>Smarty.init()</code> with <code>@PostConstruct</code> but this did not change anything. </p>
  
  <p>Note that the first thing <code>Smarty.init()</code> does is calling <code>buildingService.getAll();</code></p>