Autowired类在构造函数中为null
我具有以下代码结构,其中Bar类的Autowired Foo类为空。在Bar中尝试了Foo的已创建对象,但是@Autowired Doo变为null。
@Service
public class Doo{
public String getString(){
return "String";
}
}
@RestController
@Component
@RequestMapping(value = "/do/something", method = RequestMethod.GET)
public class Foo {
@Autowired
private Doo doo;
// method
public String getString(){
return doo.getString();
}
}
@Component
public final class Bar {
@Autowired
Foo foo;
private static final Bar bar = new Bar();
private Bar (){
foo.getString();
}
public static Bar getInstance(){
return bar;
}
}
您的代码有点混乱,因为Bar
不执行任何操作。
我测试了以下代码,它正在运行:
Foo.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Component
public class Foo {
@Autowired
private Doo doo;
@RequestMapping(value = "/do/something", method = RequestMethod.GET)
public String getString() {
return doo.getString();
}
}
Doo.java
import org.springframework.stereotype.Service;
@Service
public class Doo {
public String getString() {
return "String";
}
}
实例化控制器不是最佳实践,因为业务逻辑应该放在Service类上。
正如@ benji2505所指出的,您的问题也有一些错别字。
我将RequestMapping批注更改为方法级别,您可以像以前一样保留,但是您还需要按照以下方式向该方法添加一个RequestMapping:can anybody explain me difference between class level controller and method level controller..?
在Bar
类中,您编写了@Autowire Foo foo;
,这是不正确的。
应该是:@Autowired
,而不是@Autowire
。
此外,当您用@RestController
注释类时,您不需要添加@Component
注释,因为@RestController
是@Component
的一种特殊注释(@ResponseBody
+ @Controller
的组合) 。
谢谢:)