Best Practices
This section shows some best practices for using @HttpExchange
.
Contract-Driven Development
@HttpExchange
also provides server endpoints, just like @RequestMapping
.
This makes it ideal for defining interface contracts and supporting contract-driven development.
Project structure:
.
├── order-service
│ ├── order-api
│ └── order-server
└── user-service
├── user-api
└── user-server
- order-api
- order-server
- user-api
- user-server
@HttpExchange("/orders")
public interface OrderApi {
@GetExchange("/by_user/{userId}")
List<OrderDTO> getOrdersByUserId(@PathVariable("userId") String userId);
}
@RestController
public class OrderApiImpl implements OrderApi {
@Autowired
private UserApi userApi;
@Override
public List<OrderDTO> getOrdersByUserId(String userId) {
UserDTO user = userApi.getUser(userId);
if (user.getStatus() == INACTIVE) {
throw new UserInactiveException();
}
// Ignore the implementation
}
}
@HttpExchange("/users")
public interface UserApi {
@GetExchange("/{id}")
UserDTO getUser(@PathVariable("id") String id);
}
@RestController
public class UserApiImpl implements UserApi {
@Override
public UserDTO getById(String id) {
// Ignore the implementation
}
}