0

I created a spring boot app with application.properties containing this:

spring.data.mongodb.uri=mongodb://localhost:27017/product-service

I also added a new connection in my MongoDB Compass with this URI: mongodb://localhost:27017/product-service

But for some reason, I get NPE when I try to get something from the repo.

I did a little bit of research and did the following steps to fix the issue, but I couldn't solve it:

  1. I verified that MongoDB is running by accesing the URI
  2. I made sure that I created a database with this name "product-service" in MongoDB Compass.
  3. When I enable MongoDB logging I see nothing related to mongo.

Here are the logs when I try to get something from the repository:

java.lang.NullPointerException: null
    at com.emanuel.productservice.controller.ProductController.getAllProducts(ProductController.java:29) ~[main/:na]

Here is my controller:

@RestController
@RequestMapping("api/product")
@RequiredArgsConstructor
public class ProductController {

    private ProductService productService;

    @GetMapping
    @ResponseStatus(HttpStatus.OK)
    public List<ProductResponse> getAllProducts(){
        return productService.getAllProducts();
    }

}

Here is my service:

@Service
@RequiredArgsConstructor
@Slf4j
public class ProductService {

    private final ProductRepo productRepo;

    public List<ProductResponse> getAllProducts() {
        List<Product> products = productRepo.findAll(); // here is the line where I get NPE
        return products.stream().map(this::mapToProductResponse).collect(Collectors.toList());
    }
}

Here is my repository:

public interface ProductRepo extends MongoRepository<Product, String> {

}

I have MongoDB Community Server version 6.0.4 (current) & Spring Boot 2.7.8. This is the dependency that I use in Gradle:

implementation 'org.springframework.boot:spring-boot-starter-data-mongodb
noob234
  • 199
  • 2
  • 12
  • 1
    This suggests that `productRepo` is null. Without a [mre] it is impossible to diagnose this in more detail. – Mark Rotteveel Feb 22 '23 at 10:20
  • 1
    I join @MarkRotteveel - without a minimal reproducible example, it is impossible to investigate and diagnose this in more detail. For example, Spring boot 2.7.8 is not the latest version, as far as I know, Spring 3.0.0 was released on November 24th, 2022 and by now there's even 3.1.0 or even later (did you check the version of Spring Boot in your project imported dependencies?). To be safe, state the Spring Boot version in the dependency. – Binyamin Regev Feb 22 '23 at 10:42
  • I updated, my question. Hopefully is ok now :) – noob234 Feb 22 '23 at 17:09

0 Answers0