spring集成mongodb簡單使用和測試方式

@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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章