once
once

Reputation: 702

When is setter injection being called in the bean life cycle

I once read that for setter injection, the dependencies are not injected until they are needed. However, when I run a little test on that, I see that in using setter injection, dependencies are injected at application startup time. Actually, when is setter injection being called in the Spring bean life cycle ? and what does it mean by "dependencies are not injected until they are needed" ?

@Service
public class MainService {

  private DependencyService dependencyService;

  @Autowired
  public void setDependencyService(DependencyService dependencyService) {
    this.dependencyService = dependencyService;
  }

  @PostConstruct
  public void afterConstruct() {
    System.out.println("Created MainService bean");
    if (service != null) {
      System.out.println("DependencyService is injected");
    }
  }
}

@Service
public class DependencyService {

  @PostConstruct
  public void afterConstruct() {
    System.out.println("created DependencyService bean");
  }
}

On application startup, the console result:
Created DependencyService bean
Created MainService bean
DependencyService is injected

Upvotes: 2

Views: 788

Answers (1)

Ken Chan
Ken Chan

Reputation: 90467

Dependencies are always injected right after or during the bean is instantiated no matter you use field injection , setter injection or constructor injection .

So it depends on when the bean is initialised. By default all beans will be initialised eagerly at startup which means that their dependencies are also injected at startup

It is generally a desirable behaviour as it allows you to discover error due to bean configuration at startup rather than several hours or even days later.

You can change a bean to be lazy initialised until they are needed by annotating it as @Lazy. So if you want MainService to be lazy initialised until it is accessed (i.e. its setter injection does not happen at start up) , you have to :

@Service
@Lazy
public class MainService {

} 

Upvotes: 3

Related Questions