spring Dependency Injection (DI) and Inversion of Control (IoC) Injecting a dependency manually through Java configuration


Example

The same examples as shown above with XML configuration can be re-written with Java configuration as follows.

Constructor injection

@Configuration
class AppConfig {
  @Bean
  public Bar bar() { return new Bar(); }

  @Bean
  public Foo foo() { return new Foo(bar()); }
}

Property injection

@Configuration
class AppConfig {
  @Bean
  public Bar bar() { return new Bar(); }

  @Bean
  public Foo foo() {
    Foo foo = new Foo();
    foo.setBar(bar());

    return foo;
  }
}