简体   繁体   中英

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

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 (ie its setter injection does not happen at start up), you have to:

@Service
@Lazy
public class MainService {

} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM