首页 文章

Spring MongoRepository,在哪里捕获异常?

提问于
浏览
2

我有一个Spring项目和一个MongoRepository . MongoRepository是一个扩展MongoRepository的接口,就像JPA一样 .

如果我尝试用 mvn clean install 构建我的项目,它会运行Spring一次 . Spring尝试连接到我的Jenkins服务器上没有运行的MongoDB .

exception = {com.mongodb.MongoSocketOpenException:Exception opening socket},由{java.net.ConnectException:Connection refused:connect}引起

有没有办法捕捉异常?我无法在我调用我的存储库的服务上捕获它,因为这些方法没有被执行 . 我认为它与 @autowire 有关,但我无法弄清楚如何捕获异常 .

架构:

application
  - resource (api)
  - service
  - repository extends MongoRepository

应用程序扫描项目,资源调用服务,服务调用存储库,存储库抛出错误,因为它无法连接到MongoDB .

Repository:

public interface MetingRepository extends MongoRepository<Meting, String> {
    Page<Meting> findAllByRuimteId(String ruimteId, Pageable page);
}

Service:

@Service("metingenService")
public class MetingServiceImpl implements MetingService {

  // could I try-catch this?
  @Autowired
  private MetingRepository metingRepository;

    @Override
    public Meting addMeting(Meting meting) {
      // try-catch does not solve the issue here
      return metingRepository.save(meting);
    }
  }
}

我自己生成的唯一 test

@RunWith(SpringRunner.class)
@SpringBootTest
public class MetingenServiceApplicationTests {

    @Test
    public void contextLoads() {

    }

}

Stacktrace:

org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为'metingResource'的bean时出错:通过字段'metingService'表示的不满意的依赖关系;嵌套异常是org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为'metingenService'的bean时出错:通过字段'metingRepository'表示的不满意的依赖关系;嵌套异常是org.springframework.beans.factory.BeanCreationException:创建名为'metingRepository'的bean时出错:在设置bean属性'mongoOperations'时无法解析对bean'mongoTemplate'的引用;嵌套异常是org.springframework.beans.factory.BeanCreationException:在类路径资源中定义名为'mongoTemplate'的bean时出错[org / springframework / boot / autoconfigure / data / mongo / MongoDataAutoConfiguration.class]:通过工厂方法进行Bean实例化失败;嵌套异常是org.springframework.beans.BeanInstantiationException:无法实例化[org.springframework.data.mongodb.core.MongoTemplate]:工厂方法'mongoTemplate'抛出异常;嵌套异常是org.springframework.dao.DataAccessResourceFailureException:在等待与WritableServerSelector匹配的服务器的30000毫秒后超时 . 群集状态的客户端视图是{type = UNKNOWN,servers = [{address = localhost:27017,type = UNKNOWN,state = CONNECTING,exception = {com.mongodb.MongoSocketOpenException:Exception opening socket},由{java.net引起 . ConnectException:连接被拒绝:连接}}];嵌套异常是com.mongodb.MongoTimeoutException:在等待与WritableServerSelector匹配的服务器时30000 ms后超时 . 群集状态的客户端视图是{type = UNKNOWN,servers = [{address = localhost:27017,type = UNKNOWN,state = CONNECTING,exception = {com.mongodb.MongoSocketOpenException:Exception opening socket},由{java.net引起 . ConnectException:连接被拒绝:连接}}]

1 回答

  • 1

    您的单元测试正在尝试加载完整的Spring Context . 因此,它正在尝试加载有效的 MongoTemplate 以连接到MongoDB实例 .

    在大多数情况下,您不应该使用 @SpringBootTests (用于集成测试),而是可以执行正常的JUnit测试:

    @RunWith(JUnit4.class) // or @RunWith(MockitoJUnitRunner.class)
    public class MetingenServiceApplicationTests {
        ...
    }
    

相关问题