[英]Why does @Autowired work in my Controller but not in my Service?
In the MyController
, @Autowired
works fine to pull in myService
without getters/setters:在
MyController
中, @Autowired
可以很好地在没有 getter/setter 的情况下引入myService
:
@Controller
public class MyController
{
@Autowired
private MyService myService;
But when I try to apply the @Autowired
annotation to the myOtherService
field of MyService
, I get an error saying it can't find a necessary setter method for myOtherService
-- but it works if I fill in the getter and setter methods for this field:但是,当我尝试将
@Autowired
注释应用到MyService
的myOtherService
字段时,我收到一条错误消息,指出它找不到myOtherService
的必要 setter 方法——但如果我为此字段填写 getter 和 setter 方法,它就可以工作:
THIS WORKS:这有效:
@Service
public class MyService
{
private MyOtherService myOtherService;
public void setMyOtherService(MyOtherService myOtherService)
{
this.myOtherService = myOtherService;
}
public MyOtherService getMyOtherService()
{
return myOtherService;
}
THIS DOESN'T WORK:这不起作用:
@Service
public class MyService
{
@Autowired
private MyOtherService myOtherService;
Does @Autowired
only work on controllers? @Autowired
是否仅适用于控制器?
You gave your answer - you don't have <context:component-scan />
for the service package.您给出了答案 - 您没有服务 package 的
<context:component-scan />
。 If you add it, you'll have annotation autowiring如果添加它,您将拥有注释自动装配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.