I am new to SpringBoot. I have built a simple application which should use fake data in the development environment, and connect to MongoDb in the test environment. Dev environment does not have mongodb setup.
I have tried using Spring Boot qualifiers/profiles to achieve it.
I have a main class which looks like the following:
@SpringBootApplication public class Main { public static void main(String[] args) { SpringApplication.run(Main.class, args); } } I have a DAO interface StudentDao.java
public interface StudentDao { Student getStudentById(String id); } I then created a couple of implementations for the DAO, one for fake data, and one for data from Mongo
FakeStudentDaoImpl.java
@Repository @Qualifier("fakeData") public class FakeStudentDaoImpl implements StudentDao { private static Map<String, Student> students; static { students = new HashMap<String, Student>(){ { put("1", new Student("Ram", "Computer Science")); } }; } @Override public Student getStudentById(String id){ return this.students.get(id); } } MongoStudentDaoImpl.java
@Repository @Qualifier("mongoData") public class MongoStudentDaoImpl implements StudentDao { @Autowired private MongoStudentRepo repo; @Override public Student getStudentById(String id) { return repo.findById(id).get(); } } The MongoStudentRepo is a simple interface extending MongoRepository:
public interface MongoStudentRepo extends MongoRepository<Student, String> { } And my POM file has the following dependencies called out:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> Of course, I have other controller classes. This works fine in the Test environment, where there is a MongoDb, and it is able to connect to it. However, when I am trying to start it in my local environment, it fails to start because it is not finding MongoDb on startup.
How do I disable the MongoDb part in my local environment (and just use fake data)? I want to make the same code work in both environments.
Thanks in advance.
localanddevenvironment just use in memoryH2database, you don't need to change anything other than configs