Reasons for delegating bean registration

31 views Asked by At

I had a question while writing to test auto-configuration.

@Configuration
public class SimpleConfiguration {
    @Bean
    public BigDecimal aDecimal( String example ) {
        return new BigDecimal( example );
    }
}
@Configuration
public class BigDecimal {
    
}

I think the above two codes have the same result of registering BigDecimal object as bean. However, if you look at the example of auto-configuration, it is implemented with the code above. Why use the code above if the two results are the same

1

There are 1 answers

0
knittl On

The first form gives you much more flexibility:

  • Default parameter values
  • Multiple bean instances of the same type
  • Wiring (private) dependencies that are not beans themselves
  • Registering classes as beans without touching those classes (you might not have access to the classes' source code, external libraries, etc.)