-
Notifications
You must be signed in to change notification settings - Fork 35
/
Application.java
73 lines (57 loc) · 2.38 KB
/
Application.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.github.zarathustra;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.github.zarathustra.domain.Person;
import com.github.zarathustra.mongo.MultiTenantMongoDbFactory;
import com.github.zarathustra.service.PersonRepository;
import com.mongodb.Mongo;
@Configuration
@EnableAutoConfiguration
public class Application implements CommandLineRunner {
@Autowired
MongoTemplate mongoTemplate;
@Autowired
PersonRepository personRepository;
@Bean
public MongoTemplate mongoTemplate(final Mongo mongo) throws Exception {
return new MongoTemplate(mongoDbFactory(mongo));
}
@Bean
public MultiTenantMongoDbFactory mongoDbFactory(final Mongo mongo) throws Exception {
return new MultiTenantMongoDbFactory(mongo, "test");
}
// just to make it as simple as possible.
private Person createPerson(final String name, final String surename, final long age) {
Person p = new Person();
p.setName(name);
p.setSurname(surename);
p.setAge(age);
return p;
}
@Override
public void run(final String... args) throws Exception {
// add something to the default database (test)
this.personRepository.save(createPerson("Phillip", "Wirth", ChronoUnit.YEARS.between(
LocalDate.of(1992, Month.FEBRUARY, 3),
LocalDate.now())));
System.out.println("data from test: " + this.personRepository.findAll());
// okay? fine. - lets switch the database
MultiTenantMongoDbFactory.setDatabaseNameForCurrentThread("test666");
// should be empty
System.out.println("data from test666: " + this.personRepository.findAll());
// switch back and clean up
MultiTenantMongoDbFactory.setDatabaseNameForCurrentThread("test");
this.personRepository.deleteAll();
}
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
}