【发布时间】:2015-04-25 20:47:37
【问题描述】:
假设我有一个组件类,我已经自动装配了一个服务类。喜欢
@Autowired
private MyService myService;
然后如果我想从同一类的私有方法中使用它,例如,
private void callService(){
myService.servmMthod();
}
它会给我们一个空指针,因为这里的 myService 是空的,但是如果方法像下面这样是公共的就可以了
public void callService(){
myService.servmMthod();
}
您能解释一下为什么会这样吗?
根据评论:
@Component
public class MyDemo {
@Autowired
private MyService myService;
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"spring.xml");
Customer c1 = null;
MyDemo myDemo = ctx.getBean(MyDemo.class);
myDemo.callService(ctx);
}
private void callService(ApplicationContext ctx) {
System.out.println(myService);
myService.callMydao();
}
}
如果callService 是公开的,则其工作正常,否则myService 为空。
【问题讨论】:
-
你有 myService 的 getter 和 setter 吗?把@Autowired注解也放在那里。
-
向我们展示整个课程,从那里你调用你的私有方法。
-
我认为您没有关注正确的方面。一个字段要么有值,要么没有值,它与你读取它的方法无关。我的猜测:您正在从构造函数调用私有方法,或者从在 bean 生命周期中过早执行的另一段代码(在连接属性之前)调用私有方法。如果不是这样,那么您很有可能正在做一些时髦的并发访问。
-
你能分享你的代码吗?
-
Vishnudev K,不,我没有任何用于 myService 的 setter 和 getter