Spring Boot:将存储库注入服务层中定义的 class

SpringBoot: Inject repository into a class defined in service layer

我在 SO 上搜索了类似的问题,但是没有找到非常具体的答案。 我是 Springboot 的新手。我在服务层定义了一个 POJO。我想将存储库注入此 class。不知何故,它总是出现 null。这是我的代码结构,

文件:service/ResultInstitute.java

@Document(indexName = "result_institute")
public class ResultInstitute implements Serializable {


@Inject
public CourseRepository courseRepository;

/**
 * 
 */
private static final long serialVersionUID = -2168910694195614091L;

public ResultInstitute(Institute institute)  {

    // Initialize all the values.

    for (Course course : institute.getCourses()){
        HashMap<String, String> courseDetails = courseRepository.getCourseDetails(course.getId());
        course.setCourseDetails(courseDetails);
        courses.add(course);
    }
    courses       = institute.getCourses();

    for (Course course : courses){
        subCategories.put(course.getSubCategory().getId(), course.getSubCategory().getDisplayName());
        categories.put(course.getSubCategory()
                             .getCategory()
                             .getId(), 
                       course.getSubCategory()
                             .getCategory()
                             .getDisplayName());
    }
}

public ResultInstitute (){}

private Long id;

private String code; ....

文件:repository/CourseRepository.java

public interface CourseRepository extends JpaRepository<Course,Long> {

@Query("select distinct course from Course course left join fetch course.institutes")
List<Course> findAllWithEagerRelationships();

@Query("select course from Course course left join fetch course.institutes where course.id =:id")
Course findOneWithEagerRelationships(@Param("id") Long id);

@Query(value="SELECT DISTINCT(ci.course_details) FROM course_institute ci WHERE ci.courses_id = ?1", nativeQuery = true)
HashMap<String, String> getCourseDetails(Long id);

}

每当我尝试使用 courseRepository 时,它都会给我 NullPointerException。你能帮我解决这个问题吗?

您需要用 @Component 注释您的 ResultInstitute。这告诉 spring 它必须注入依赖项。

将其添加到您的构造函数中 @Document(indexName = "result_institute") public class ResultInstitute 实现 Serializable {

    public CourseRepository courseRepository;

    @Autowired
    public ResultInstitute (Institute institute, CourseRepository courseRepository) {
        this.courseRepository = courseRepository;
    }
}

你在评论区说你发起 ResultInstitute class 如下,

ResultInstitute resultInstitute = new ResultInstitute(i); resultInstitute.locationFilterString(i);

初始化是自己处理的,所以@Autowired在这种情况下不起作用。 @Autowired 是用于注入 bean 的 spring 配置,因此为了注入 Repository ResultInstitute 应该由 Spring Iteself 处理。

我们必须告诉 spring ResultInstitute 是 bean class 因为你可以将 ResultIntitute class 注释为 @Component

@Component 
public class ResultInititute

因此,每当您想实例化 ResultInstitute 时,使用 @Autowired

实例化为 bean class
@Autowired
ResultInstitute resultInstitute;

And Using the Respository in Entity class is not good thing, we have to handle this in separate section.