Dependency Injection - Tuong-Nguyen/Spring GitHub Wiki

Dependency Injection

Java-based

Annotations

@AutoWired

XML

Constructor vs. Setter injection

public class Game{
   // Construction injection
   public Game(Team home, Team away){
      // ...
   }

   // Setter injection
   public void setDataSource(DataSource dataSource){
      // ...
   }
}

Constructor: mandatory dependency
> Only one constructor is autowired

Setter: optional dependency - Client is able to not call the setter and the class uses the default dependency.

Bean Scope

Game game1 = context.getBean("game", Game.class);
Game game2 = context.getBean("game", Game.class);

Q: game1 and game2 refer to the same Game instance or they are referring to 2 Game instances?
A: Single

By default, all Spring managed beans are singletons!

Scope types

  • singleton (default)
  • prototype: create new instance every time the bean is injected into or retrieved from the Spring application context.
  • request (web environment): one instance of the bean is created for each request.
  • session (web environment): one instance of the bean is created for each session.

Scope config

Use @Scope annotation with @Component or @Bean

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class Notepad { ... }
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Notepad notepad() {
    return new Notepad();
}

Initialization & Destruction

Initialization: After an instance is created, we need to do some configuration on the instance.
Destruction: Before an instance is deleted, we need to do some cleanup on the instance.

  1. Option 1: @Bean
public class AppConfig {

   @Bean(initMethod = "startGame", destroyMethod = "endGame")
   public Game game(){
      return new Game();
   }

startGame method of Game is called after the instance is created.
endGame method of Game is called before the instance is destroyed.

  1. Option 2: @PostConstruct - @PreDestroy
public class Game {
   @PostConstruct
   public void startGame(){
   }

   @PreDestroy
   public void endGame(){
   }

Option 1 vs Option 2:

  • Option 2 is preferred if we own the class.
  • Option 1 is preferred when we do not own the class.