eclipse-ee4j / eclipse-ee4j/jersey

Bind @BeanParam using a custom builder such as immutables.io

Open
#4,422 0 comments 0 reactions 0 assignees View on GitHub
Type: New Feature
Dominant language
Java
Stars
730
Forks
382
PR merge metrics
No merged PRs in 30d

Description

Our project uses immutables.io to for its models. For methods that take several parameters, we wanted to box these parameters into a request object to improve readability and testing.

For consistency it would be nice to continue using immutables with these request objects. However, I could not find a way to customise `@BindParam` to support builders.

## Example

```java
public class Controller {
@GET @Path("items/{foo}")
public Response get(@BeanParam ItemRequest request) {
...
}
}

@Value.Immutable
public interface ItemRequest {
@PathParam("foo") String foo();
@QueryParam("bar") String bar();
}
```

## Workaround
It is possible to bind an immutable class using a builder if you create it yourself by using a second level of indirection on the `@BeanParam`. The downside is you have to write all the boilerplate instead of letting immutables generate it for you.

```java
public class Controller {
@GET @Path("items/{foo}")
public Response get(@BeanParam ItemRequest request) {
...
}
}

public class ItemRequest {
private final String foo;
private final String bar;

public ItemRequest(@BeanParam Builder builder) {
this.foo = builder.foo;
this.bar = builder.bar;
}

public static class Builder {
private String foo;
private String bar;

@PathParam("foo")
public Builder foo(final String foo) {
this.foo = foo;
return this;
}

@QueryParam("bar")
public Builder bar(final String bar) {
this.bar = bar;
return this;
}

public ItemRequest build() {
return new ItemRequest(this);
}
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.