简体   繁体   中英

Spring setter injection guarantee

Is it safe to move form constructor injection to setter injection ?

Does setter injection guarantee that my object is fully constructed at usage time?

Yes it is safe.

With constructor injection , Spring will call the constructor with appropriate arguments (note that in this case you can add the final modifier to your dependencies field).

Sample

private final SomeBean dependency;

public MyObject(SomeBean dependency){
    this.dependency = dependency;
    doInit();
}

private void doInit(){
    //doStuff to initialize your bean
}

With setter injection , Spring will instantiate your bean using the default constructor (ie no arg constructor). Next step is calling all required setters so that all @Autowired dependencies are set. Finally Spring will call methods with @PostConstruct annotation.

Sample

@Autowired
private SomeBean dependency;

@PostConstruct
private void doInit(){
    //doStuff to initialize your bean
}

Using setter injection have one advantage: in case of circular dependencies between your beans, Spring will be able to resolve them (because it can invoke a setter with a partially build bean ). (it's ok if your setters are real setters and do anything more than assigning a value to a field)

On the other hand, Spring fails to resolve circular dependencies when using constructor injection, simply because a partially build bean cannot decently be used as constructor argument.

I'm a little late to the party, but here are my 2 cents in 2 points,

  • In any OO language setter/field injection is evil .
  • It is better to fail fast due to a Circular dependency Injection, as it is a design error. And not noticing them could adversely affect you latter on.

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