The key to define a Mock Repository is the @Repository annotation. @Repository is a Spring annotation that indicates that the decorated class is a repository.

A Repository is a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects. It is a specialization of the @Component annotation allowing for implementation classes to be autodetected through classpath scanning.

spring boot mock in memory repository

Let's start from a simple interface:

package com.sample;

import java.util.List;

public interface CustomerRepository {

	List<Customer> findAll();
	Customer findCustomer(Long id);


Now we will define an implementation of this interface that is tagged with @Repository:

package com.sample;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

public class MockCustomerRepository implements CustomerRepository {

	private final List<Customer> customers = new ArrayList<>();

	public MockCustomerRepository() {
		this.customers.add(new Customer(1L, "John", "Smith"));
		this.customers.add(new Customer(2L, "Mark", "Spencer"));
		this.customers.add(new Customer(3L, "Andy", "Doyle"));

	public List<Customer> findAll() {
		return this.customers;

	public Customer findCustomer(Long id) {
		for (Customer customer : this.customers) {
			if (ObjectUtils.nullSafeEquals(customer.getId(), id)) {
				return customer;
		return null;


Here is how to use the Mock Repository in a Spring Boot application:

package sample.hateoas;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.sample.Customer;
import com.sample.MockCustomerRepository;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DemoApplication {
    private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);

    public static void main(String[] args) {, args);
    public CommandLineRunner demo(MockCustomerRepository repository) {
        return (args) -> {
  "Customers found with findAll():");
            for (Customer person : repository.findAll()) {

            // fetch an individual customer by ID
  "Customer 1 " + repository.findOne(1L).getLastName());