问题很简单,但我解决不了。据我所知,字段首先初始化,然后调用构造函数。
以下代码
public class Controller {
@Inject
private ReadCommand readCommand;
public Controller() {
if (readCommand==null){
System.out.println("NO");
}else{
System.out.println("YES");
}
}
}
打印。但是当我注入constructor
@Inject
public Controller(ReadCommand readCommand)
打印YES。我做错了什么?
你没做错什么。在注入过程中,构造函数被调用多次。只有在构建了托管bean之后,这些字段才会被注入到该bean中。当你做构造函数级注入时,你的构造函数需要读:
private ReadCommand readCommand;
@Inject
public Controller(ReadCommand readCommand) {
this.readCommand = readCommand;
if(this.readCommand == null) {
...
}
}