It depends on the language / templates that you choose, since some of them are more flexible than others, but the same principle holds true: You shouldn't be adding any additional logic in the generated code. Unfortunately, by looking at the sample for jaxrs-spec
, these templates don't look as good as the ones for say, jaxrs-resteasy
.
At this point, you can either:
- Switch templates to a different
jaxrs
- Write your own templates and use them instead
- Modify / update the swagger-codegen templates and commit them back.
I'll walk through an explanation of how this is done for the other templates. The way this is currently done is through factories, but it could just as easily be done with dependency injection. Codgen generates stub implementations that are the boilerplate to stand up the API, and delegates the actual logic to another class.
For jaxrs-resteasy
, here's what codegen generates for a GET /{username}
method (I removed the swagger annotations it also puts in):
@GET
@Path("/{username}")
@Produces({ "application/xml", "application/json" })
public Response getUserByName( @PathParam("username") String username,@Context SecurityContext securityContext)
throws NotFoundException {
return delegate.getUserByName(username,securityContext);
}
The actual method just delegates to a factory, which it obtains like so:
private final UserApiService delegate = UserApiServiceFactory.getUserApi();
It can do this because it also generates a base class for the API to implement:
public abstract class UserApiService {
// methods omitted...
public abstract Response getUserByName(String username, SecurityContext securityContext) throws NotFoundException;
// methods omitted...
}
Now, in non-generated code, the user adds an implementation of this base class:
public class UserApiServiceImpl extends UserApiService {
// methods omitted...
@Override
public Response getUserByName(String username, SecurityContextsecurityContext) throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
}
// methods omitted...
}
And then, the user adds the factory in the package that codegen expects, so the generated code can obtain the above implementation:
public class UserApiServiceFactory {
private final static UserApiService service = new UserApiServiceImpl();
public static UserApiService getUserApi() {
return service;
}
}
Now the code that was generated knows exactly which implementation of UserApiService
to delegate to. At this point, the entire server boilerplate is separated from the application logic, allowing you to regenerate the API without overwriting your custom logic.
This answer assumes that the sample for jaxrs-spec
is an accurate example of what swagger-codegen produces for that language parameter. Sometimes they get out of date.