Configure multiple Beans

Viewed 33

What is the difference in using the Spring Beans for instantiating different Beans of the same type (with other beans as input).

Suppose I have bean configured with some properties as follows

  @Bean(name = "product")
   @ConfigurationProperties(prefix = "products")
   public DataSource createProductServiceDataSource() {
      return DataSourceBuilder.create().build();
   }

Now I usually see two options of using this bean as Input for instantiating another bean but what exactly is the difference because they usually produce the same output (two examples below):

@Bean(name = "exampleOne")
   @Autowired
   public JdbcTemplate createJdbcTemplate_ProductService(@Qualifier("product") DataSource productServiceDS) {
      return new JdbcTemplate(productServiceDS);
   }

@Bean(name = "exampleTwo")
   @Autowired
   public JdbcTemplate createJdbcTemplate_ProductService(DataSource createProductServiceDataSource() ) {
      return new JdbcTemplate(productServiceDS);
   }


And also for the second example: That still seems to work, even when I remove the @Bean annotation from the #createProductServiceDataSource() method.

0 Answers
Related