Mavenの依存関係設定
プロジェクト構成に必要なライブラリを宣言します:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
</dependencies>
Jerseyコンフィギュレーション
RESTリソースのスキャン対象パッケージを指定します:
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ApiConfig extends ResourceConfig {
public ApiConfig() {
registerPackages("com.example.api.endpoints");
}
}
エンドポイント実装
HTTPリクエスト処理の核心ロジックを記述します:
@Component
public class UserEndpoint {
private final Map<String, UserData> userStore = new ConcurrentHashMap<>();
@POST
@Path("/v1/users/submit")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response submitUser(
@FormParam("uid") String userId,
@FormParam("username") String userName) {
UserData record = new UserData(userId, userName);
userStore.put(userId, record);
return Response.ok().build();
}
パラメータ処理の実装パターン
パスパラメータの取得例:
@GET
@Path("/v1/users/{userId}")
public UserData fetchUser(@PathParam("userId") String id) {
return userStore.get(id);
}
複数IDによる一括処理:
@DELETE
@Path("/v1/users/batch")
public Response deleteUsers(@QueryParam("userIds") List<String> ids) {
ids.forEach(userStore::remove);
return Response.noContent().build();
}
JSONペイロードの処理:
@POST
@Path("/v1/users/profile")
@Consumes(MediaType.APPLICATION_JSON)
public Response saveProfile(UserData profile) {
userStore.put(profile.getId(), profile);
return Response.accepted().build();
}
@POST
@Path("/v1/users/batch")
@Consumes(MediaType.APPLICATION_JSON)
public List<UserData> fetchBatch(List<String> userIds) {
return userIds.stream()
.map(userStore::get)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}