由于MongoDB中@Document注解适用于实体类上,所以项目的开始就写死了集合名:
@Document(collection = "test")
但是随着项目的进行,需要动态配置此处的集合名,于是我就开始尝试动态配置
动态配置:
mongoDB之@Document(collection = "#{personRepository.getCollectionName()}")
首先创建一个@Configuration类:
@Configuration public class MongodbCollectionConfig { @Value("${spring.data.mongodb.collection-name}") private String collectionName; @Bean public String mongodbCollectionName(){ return collectionName; } }
配置文件中:
spring.data.mongodb.collection-name=test
Java代码:
@Document(collection = "#{personRepository.getCollectionName()}") public class Person{} public interface PersonRepository extends MongoRepository<Person, String>, PersonRepositoryCustom{ } public interface PersonRepositoryCustom { String getCollectionName(); void setCollectionName(String collectionName); } public class PersonRepositoryImpl implements PersonRepositoryCustom { private static String collectionName = "Person"; @Override public String getCollectionName() { return collectionName; } @Override public void setCollectionName(String collectionName) { this.collectionName = collectionName; } } @Autowired PersonRepository personRepository; public void testRetrievePeopleFrom2SeparateCollectionsWithSpringRepo(){ List<Person> people = new ArrayList<>(); personRepository.setCollectionName("collectionA"); people.addAll(personRepository.findAll()); personDocumentRepository.setCollectionName("collectionB"); people.addAll(personRepository.findAll()); Assert.assertEquals(4, people.size()); }
或者直接写在类上:
@Document(collection = "#{@getCollectionName}", collation = "zh") @Data public class CustomFormMongoEntity implements Serializable {