简体   繁体   中英

CDI order of injecting and constructor

Simple question, but I can't solve it. As I know fields are initialized first and after that constructor is called.

The following code

public class Controller {

        @Inject
        private ReadCommand readCommand;

        public Controller() {
            if (readCommand==null){
                System.out.println("NO");
            }else{
                System.out.println("YES");
            }        
        }
}

prints NO. But when I inject in constructor

@Inject
public Controller(ReadCommand readCommand)

It prints YES. What am I doing wrong?

You're doing nothing wrong. The constructor is called many times during the injection process. The fields are injected into the managed bean only once it's been constructed. When you do constructor level injection, your constructor needs to read:

private ReadCommand readCommand;

@Inject
public Controller(ReadCommand readCommand) {
    this.readCommand = readCommand;
    if(this.readCommand == null) {
        ...
    }
}

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