【问题标题】:@Autowired for the interface inside the class object is null [duplicate]类对象内部接口的@Autowired为空[重复]
【发布时间】:2018-07-07 00:15:58
【问题描述】:

我在我的项目中使用 MVC 设计模式,我有一个名为 SchoolRepository 的接口,我有一个控制器类,我在其中声明了学校存储库接口,我也在模型类中声明了学校存储库接口,当我调用时我从控制器编写逻辑的模型类对象我收到空指针异常,因为在服务类中声明的学校接口为空

下面是我的控制器类

    @RestController 
    @RequestMapping("University")
    public class Controller{

        //interface declaration
        @Autowired
        SchoolRepository  schoolRepository;

        @GetMapping("student")
        public list getStudent(){

           Service s=new Service();
           List list=s.getStudents();
           return list;
        }
        .
        .
    }

下面是我的模型类

      public class Service(){

      @Autowired
      SchoolRepository schoolRepository;

      public List getStudents(){
      return schoolRepository.getAll();
      }

下面是仓库类

           @Repository
           public interface SchoolRepository extends JpaRepository<School, Long>{}

我在使用 schoolRepository 的服务类中得到一个空点异常,当我使用 System.Out.Println 检查 s.schoolRepository 的值时,我得到空值.. 如何初始化接口以及如何在其中使用它服务等级

【问题讨论】:

  • 分别将 @Service@Repository 添加到您的服务和 repo 类中
  • 我确实添加了这两个,但我仍然得到相同的空指针异常

标签: java model-view-controller interface autowired


【解决方案1】:

当您使用“new”在 Controller 类的 getStudent() 方法中实例化服务类时,spring 容器不会出现。由于服务对象不是由 Spring 容器创建的,因此“schoolRepository”不会在您的“Service”类中自动装配,因此它将为空。 因此,将 Service 类标记为 @Service 以使 spring 容器负责实例化。然后,不要使用“new”创建服务对象,而是在 Controller 类中自动装配服务对象。确保您的存储库类也标记为@Repository。

【讨论】:

  • 我使用了注释,而不是创建新的服务类,我 @Autowired 服务类,我仍然得到相同的异常
  • 您是否使用@Repository 注释了您的存储库类?您可以粘贴您的存储库和服务类的代码吗?
  • 看起来不错。你能粘贴你更新的控制器类吗?你已经在你的服务类上添加了@Service,对吧?
  • 问题中提到了控制器类,控制器的其余部分具有类似于上图的映射。我已经在服务类中添加了注解@Service
  • Service s=new Service() -> 这应该从控制器中的 getStudent() 中删除。好了吗?我仍然可以在上面的控制器中看到新服务对象的创建。如果使用“new”实例化,Spring 实例化的服务 bean 就不会出现。要获取 Spring 容器创建的服务 bean,您必须自动装配它。因此,像这样在控制器中自动装配服务对象 -> public class Controller{ @Autowired Service s; @GetMapping("student”) public list getStudent(){ List list=s.getStudents(); return list;
猜你喜欢
  • 2019-07-28
  • 2015-09-14
  • 1970-01-01
  • 1970-01-01
  • 2014-09-03
  • 1970-01-01
  • 2014-06-21
  • 1970-01-01
相关资源
最近更新 更多