打开pom.xml文件,添加Spring Data Rest和Spring Data Mongo依赖项:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-<b>rest</b></artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
模型类:
<b>public</b> <b>class</b> Customer implements Serializable { <b>private</b> <b>static</b> <b>final</b> <b>long</b> serialVersionUID = 1L; @Id <b>private</b> Long id; <b>private</b> String firstName; <b>private</b> String lastName; <b>private</b> <b>static</b> AtomicLong COUNTER = <b>new</b> AtomicLong(0L); @PersistenceConstructor <b>public</b> Customer() { <b>this</b>.id = COUNTER.incrementAndGet(); } @Override <b>public</b> String toString() { <b>return</b> String.format(<font>"Customer[id=%d, firstName='%s', lastName='%s']"</font><font>, id, firstName, lastName); } <b>public</b> String getFirstName() { <b>return</b> firstName; } <b>public</b> <b>void</b> setFirstName(String firstName) { <b>this</b>.firstName = firstName; } <b>public</b> String getLastName() { <b>return</b> lastName; } <b>public</b> <b>void</b> setLastName(String lastName) { <b>this</b>.lastName = lastName; } } </font>
通过扩展接口MongoRepository创建MongoDb存储库:
@RepositoryRestResource(collectionResourceRel = <font>"customer"</font><font>, path = </font><font>"customer"</font><font>) <b>public</b> <b>interface</b> CustomerRepository <b>extends</b> MongoRepository<Customer, String> { List<Customer> findByLastName(@Param(</font><font>"name"</font><font>) String name); } </font>
在上面的代码中,我们定义了一个自定义方法,用于按姓氏查找列表客户。
打开application.properties来配置MongoDB:
spring.data.mongodb.database=restapi spring.data.mongodb.port=27017
运行MongoDB服务器。然后运行Spring Boot项目。
GET请求:localhost:8080
源码: SpringBootMongoDbRestApi