我有一个Java Spring Framework项目。经过一段时间的搜索后,我找到了一种将自定义JPA方法包含到JpaRepository中的方法。我可以使用@Autowired将存储库注入服务类,但是在这种情况下,我无法理解Spring如何处理注入。有人可以解释当方法实现在单独的类中时,Spring如何将CalendarEventRepository注入CalendarEventService中。它在某个地方找到JpaRepository实现,并使用我的自定义方法找到我自己的自定义实现类。如何通过相同的参考变量calendarEventRepository访问它们的方法?额外的问题:Spring如何找到并实例化JpaRepository的实现?

public interface CalendarEventRepository extends JpaRepository<CalendarEvent, Long>, CalendarEventRepositoryCustom { }

public interface CalendarEventRepositoryCustom {
public List<CalendarEvent> findCalendarEventsBySearchCriteria(CalendarEventSearchCriteria searchCriteria);
}

public class CalendarEventRepositoryImpl implements
CalendarEventRepositoryCustom {
public List<CalendarEvent> findCalendarEventsBySearchCriteria(CalendarEventSearchCriteria searchCriteria) {
     }
}

public class CalendarEventService {
@Autowired
CalendarEventRepository calendarEventRepository;
...
calendarEventRepository.delete(calendarEvent);
...
return  calendarEventRepository.findCalendarEventsBySearchCriteria(searchCriteria);
...
}


提前致谢!

最佳答案

使用Spring JPA存储库接口(extend JpaRepository类)时,重要的是该接口的实现是在运行时生成的。 Spring使用方法名称来确定方法应使用的名称(因为您已经正确编写了名称findCalendarEventsBySearchCriteria,这意味着您已经知道了)。在您的特定情况下,CalendarEventRepository扩展了CalendarEventRepositoryCustom,因此具有方法findCalendarEventsBySearchCriteria(...),并且还扩展了JpaRepository<CalendarEvent, Long>,这意味着应将其视为JPA存储库,并应生成相应的实现。

要启用存储库实现的生成,您需要在XML配置文件中包含<jpa:repositories base-package="..." />@Configuration @EnableJpaRepositories(basePackage = "...")当拥有这些存储库时,这就是Spring生成(实例化)存储库并将其添加到应用程序上下文所需的全部信息。 ,然后将其注入其他bean。在您的情况下,@Autowired CalendarEventRepository calendarEventRepository;指定应在何处注入它。我猜它比主要问题更能回答奖金问题,但从它开始似乎更好。

我还没有碰过CalendarEventRepositoryImpl。如果要为特定方法删除提到的存储库实现的生成,则应使用此类。 Spring寻找一个名称等于存储库接口名称+“ Impl”的类。如果存在此类,Spring将其方法与生成的方法合并。因此,请亲自了解自动生成的findCalendarEventsBySearchCriteria方法是否适合您的需求,或者您想自己实现。如果生成的文件适合,则应考虑完全删除CalendarEventRepositoryImpl

09-17 10:11