【问题标题】:I am getting NullPointerException from spring service [duplicate]我从春季服务中得到 NullPointerException [重复]
【发布时间】:2019-03-26 13:57:16
【问题描述】:

我正在尝试使用Spring + JSF 构建一个基本网页。 基本上,我有一个HelloControllerHelloSpringService。 它在HelloController 类中返回helloSpringService.sayHello(); 行时出错。


public class HelloController {


    @ManagedProperty("#{helloSpringService)")
    private HelloSpringService helloSpringService;

    public String showHello() {

        return helloSpringService.sayHello();
    }

    public void setHelloSpringService(HelloSpringService helloSpringService) {
        this.helloSpringService = helloSpringService;
    }
    public HelloSpringService getHelloSpringService() {
        return helloSpringService;
    }

}

import org.springframework.stereotype.Service;

@Service
public class HelloSpringService {

    public String sayHello() {
        return "hellofromspringservice";
    }
}

【问题讨论】:

  • 请检查我上面评论的 SO 帖子中的答案。

标签: java spring jsf


【解决方案1】:

使用@Autowired 代替@ManagedProperty("#{helloSpringService)")

【讨论】:

  • 不完全正确...查看副本...
【解决方案2】:

您已将 bean HelloSpringService 创建为服务 bean,因此 Spring 核心负责 bean 的生命周期,因此您必须使用 @Autowired 而不是 @ManagedProperty 调用它。

【讨论】:

  • 不完全正确...查看副本...
【解决方案3】:
helloSpringService

应该是autowired,而不是作为managedproperty

【讨论】:

  • 这与其他答案有何不同(并且明显更好)?
  • 这条评论几乎是在添加其他评论的同时添加的,当我发布此评论时,我没有看到其他 cmets。可能是因为我在页面上停留的时间较长,并且在发表评论之前没有重新加载页面
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
  • 1970-01-01
  • 1970-01-01
  • 2016-07-25
  • 1970-01-01
  • 2015-10-06
  • 2019-01-19
相关资源
最近更新 更多