简体   繁体   中英

Autowiring both the constructor and the field

Is it wrong to autowire both the field and the constructor when doing the automatic configuration of the spring container. For example:

@Component
public class Test1 {

    @Autowired
    private Test2 B;

    @Autowired
      Test(Test2 C) {
      this.B=C;
    }
}

And could you explain what happened exactly ?

It's wrong. You may have two Test2 beans, one named "B" and one named "C" (names should be lowercase BTW). That constructor will be called first, setting the field to C ; after that the field will be injected, overwriting the field with B . If there is only one Test2 bean then it will work, but keep in mind that the point of constructor injection is to avoid field injection and enable use of final fields instead.

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