解决springboot无法注入JpaRepository的问题

这篇文章主要介绍了解决springboot无法注入JpaRepository的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

使用内置服务器启动springboot项目时,会从@SpringBootApplication修饰类所在的包开始,加载当前包和所有子包下的类,将由@Component @Repository @Service @Controller修饰的类交由spring进行管理。

 package com.facade; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Component; @SpringBootApplication public class Application { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(Application.class, args); String[] profiles = context.getEnvironment().getActiveProfiles(); if (profiles != null) { for (String profile : profiles) { System.out.println("------------start with profile : " + profile); } } } }

在使用Spring data jpa时,通常都是继承Repository接口相关的其他接口,然后Spring data jpa在项目启动时,会为所有继承了Repository的接口(@NoRepositoryBean修饰除外)创建实现类,并交由Spring管理。

例如,

 package com.facade.repository; import org.springframework.data.repository.PagingAndSortingRepository; import com.facade.entity.HttpDoc; public interface HttpDocRepository extends PagingAndSortingRepository { }
 package com.facade.service; import com.facade.entity.HttpDoc; public interface HttpDocService { public HttpDoc save(HttpDoc entity); public HttpDoc getById(Long id); public Iterable findAll(); }
 package com. facade.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.facade.entity.HttpDoc; import com.facade.repository.HttpDocRepository; import com.facade.service.HttpDocService; @Service @Transactional public class HttpDocServiceImpl implements HttpDocService { @Autowired private HttpDocRepository httpDocRepository; @Override public HttpDoc save(HttpDoc entity) { return httpDocRepository.save(entity); } @Override public HttpDoc getById(Long id) { return httpDocRepository.findOne(id); } @Override public Iterable findAll() { return httpDocRepository.findAll(); } } 

以上代码Application处于HttpDocRepository HttpDocServiceImpl的根目录中,所以HttpDocRepository是可以被成功注入到HttpDocServiceImpl中的。

如果将Application移动到其他平行目录或者子目录,就算使用scanBasePackages指定扫描目录也无法将HttpDocRepository成功注入,会产生如下错误描述

Action:

Consider defining a bean of type 'com.facade.repository.HttpDocRepository' in your configuration.

补充:(亲测好用的解决方法)springboot2.x整合jpaRepository中的坑

今日折腾的时候发现了一起在1.5的时候整合jpa可以使用的findOne方法突然找不到了,如下:

可以看到这个方法里面不能传入String/Integer类型的值,所以百度了一番。

有网友给了一个通过get()再取值的方法,测试了一番并无效果。通过浏览调用方法列表发现了一个getOne()的方法,返回值类型和传递的参数都符合就试了一下

测试通过

这是由于jpa懒加载的问题引起的,可以在测试关联的实体类中添加@Proxy(lazy=false)解决

测试通过

顺带想着测试一下findById()的方法也发现了一个问题

返回值变为了一个Optional<>,这个可以通过get()方法得到想要的类型值。

以上就是解决springboot无法注入JpaRepository的问题的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java