@EnableMongoRepositories @ComponentScan(basePackages = "cn.example") @Configuration public class AppConfig extends AbstractMongoClientConfiguration { // @Bean public MongoClientFactoryBean mongoClientFactoryBean() { MongoClientFactoryBean mongoClientFactoryBean = new MongoClientFactoryBean(); mongoClientFactoryBean.setMongoClientSettings(mongoClientSettings()); return mongoClientFactoryBean; } @Override protected String getDatabaseName() { // TODO Auto-generated method stub return "test"; } @Override public void configureClientSettings(Builder builder) { builder.applyConnectionString(new ConnectionString("mongodb://localhost:27017")); } }
public class Application { @SuppressWarnings("resource") public static void main( String[] args ) { AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(AppConfig.class); PersonRepository personRepository = annotationConfigApplicationContext.getBean(PersonRepository.class); Person person = new Person(); person.setName("我是iemo2"); person.setAge(21); person.setEmail("qq.Eail.com"); personRepository.insert(person); } }
源代码:https://github.com/starSmallDream/SpringIntegratedMongoDB
spring官方文档:https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-java-instantiating-container