DEV Community

eidher
eidher

Posted on • Updated on

Spring Configuration

Spring Configuration annotation indicates that the class has @Bean definition methods.
Spring @Bean Annotation is applied on a method to specify that it returns a bean to be managed by the Spring context.

@Configuration
public class ApplicationConfig {
  @Bean
  public DataSource dataSource() {
    return new DataSource();
  }
}
Enter fullscreen mode Exit fullscreen mode

Spring will create as many beans as we define in the @Configuration classes. @Configuration classes are beans too.

public class MySpringApp {
  public static void main(String[] args) {
    // Create the application from the configuration
    ApplicationContext ctx = SpringApplication.run(ApplicationConfig.class);

    // Look up the application service interface
    // Way 1: Casting
    DataSource ds1 = (DataSource) ctx.getBean("dataSource");
    // Way 2: Use typed method
    DataSource ds2 = ctx.getBean("dataSource", DataSource.class);
    // Way 3: Without been id if type is unique
    DataSource ds3 = ctx.getBean(DataSource.class);

    // Use the application
    ds1.close();
    ds2.close();
    ds3.close();
  }
}
Enter fullscreen mode Exit fullscreen mode

Creating an Application Context from Multiple Files

@Configuration
@Import({ApplicationConfig.class, WebConfig.class})
public class InfraetructureConfig {
  @Bean
  public DataSource dataSource() {
    return new DataSource();
  }
}
Enter fullscreen mode Exit fullscreen mode

Beware of duplicate beans. In the previous code, if ApplicationConfig.class and WebConfig.class have the same bean id you get the bean from WebConfig because it is the last bean. To avoid that you can use the @Order annotation.

@Configuration
@Order(1)
public class ApplicationConfig {
  @Bean
  public String example(){
    return new String("example");
  }
}
Enter fullscreen mode Exit fullscreen mode

Bean Scope

The default scope is singleton

DataSource ds1 = (DataSource) ctx.getBean("dataSource");
DataSource ds2 = (DataSource) ctx.getBean("dataSource");
assert ds1 == ds2; // True - Same object
Enter fullscreen mode Exit fullscreen mode

Prototype Scope: a new instance is created every time the bean is referenced.

@Bean
@Scope("prototype")
public DataSource dataSource() {
  return new DataSource();
}

DataSource ds1 = (DataSource) ctx.getBean("dataSource");
DataSource ds2 = (DataSource) ctx.getBean("dataSource");
assert ds1 != ds2; // True - Diferent objects
Enter fullscreen mode Exit fullscreen mode

Other scopes:

  • session
  • request
  • application
  • global
  • thread
  • websocket
  • refresh
  • Custom scopes

Top comments (0)