@Autowired constructor function

 When we need to get the object that needs to be injected in the constructor of the class:

/*@Resource
private Observer<TaxiObserverVo> taxiPushObserver;


@Resource
private Observer<TaxiObserverVo> taxiFlowObserver;



public Pay () {
super();
addObserver(taxiFlowObserver);
addObserver(taxiPushObserver);
}*/

 

@Autowired
public Pay (Observer<TaxiObserverVo> taxiPushObserver,Observer<TaxiObserverVo> taxiFlowObserver) {
addObserver(taxiFlowObserver);
addObserver(taxiPushObserver);
}

 

You can use @Autowire on constructors

 

If it is not added, an error will be reported, because

Because the Java class will execute the constructor first, and then @Autowired inject values ​​into the annotated user, an error will be reported when the constructor is executed. 

The initialization sequence of Java variables is: static variable or static statement block –> instance variable or initialization statement block –> constructor

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326333085&siteId=291194637