在MyController
中,@Autowired
可以很好地引入myService
而无需getters/setters:
@Controller
public class MyController
{
@Autowired
private MyService myService;
但是当我尝试将 @Autowired
注释应用于 MyService
的 myOtherService
字段时,我收到一条错误消息,指出它不能为 myOtherService
找到必要的 setter 方法 - 但如果我填写此字段的 getter 和 setter 方法,它就会起作用:
这个有效:
@Service
public class MyService
{
private MyOtherService myOtherService;
public void setMyOtherService(MyOtherService myOtherService)
{
this.myOtherService = myOtherService;
}
public MyOtherService getMyOtherService()
{
return myOtherService;
}
这不起作用:
@Service
public class MyService
{
@Autowired
private MyOtherService myOtherService;
@Autowired
仅适用于 Controller 吗?
最佳答案
你给出了你的答案 - 你没有<context:component-scan />
对于服务包。如果添加它,您将拥有注释 Autowiring
关于java - 为什么 @Autowired 在我的 Controller 中工作但在我的服务中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6603576/