DEV Community

Cover image for Generated by an Application That Does Nothing (Chapter 16)
Kamen
Kamen

Posted on Originally published at kamenivanov.substack.com

Generated by an Application That Does Nothing (Chapter 16)

The jar from the previous chapter is useless to two of the three people who need it.

It describes every type this API will send and accept, it is versioned on its own, and it is published where anything can depend on it. It is also Java, and the developer building the screens writes TypeScript while the engineer writing the tests uses whatever her tooling speaks. Neither of them can read a jar, and neither should have to.

So the jar was never the contract. It is one projection of the contract, the one for Java consumers, and there has to be another: a document in a format that does not belong to any language. Generating it is the obvious part. The awkward part is when. Every tool I know of reads a running application, and an application that runs is exactly what this project does not have - the service has no controllers, and will not have any for another chapter.

What follows is how a complete specification comes out of a build in which nothing is implemented.


Where a path is written down

A Swagger annotation describes an operation. It does not say where the operation lives. @Operation has a summary and @ApiResponse has a status code, and nowhere among them is a path or a verb, because those were never Swagger's job - it expects to find them in whatever framework is underneath.

So something has to say it, and the choice is which file. In the previous chapter the interfaces carried documentation and the mapping lived on the controllers that implemented them, which meant a path was written in one repository and a verb in another, and the two agreed by habit. That is the arrangement this chapter ends.

@Tag(name = "Products", description = "Managing one's own products.")
@RequestMapping(value = RestUrl.SECURED_PRODUCTS, produces = MediaType.APPLICATION_JSON_VALUE)
public interface ProductsRestService extends CrudRestService<NewProductDto, UpdateProductDto, ProductDto> {
Enter fullscreen mode Exit fullscreen mode

The mappings are on the interface. Spring supports this, with a condition stated plainly in the @RequestMapping javadoc: when using controller interfaces, put all the mapping annotations on the interface rather than on the implementation. Split between the two is the documented way to break it.

The part I expected to be a problem was the parameters, because Java does not inherit annotations on method parameters. It was a problem, until Framework 5.1, which enabled this - the issue asking for it was argued on the grounds of a REST interface shared between a client and a server. On anything current, @PathVariable and @RequestParam on an interface method are read.

The paths themselves stay in RestUrl as constants, so a path exists once as a string and is referenced by the interface, by the generated document, and later by nothing else, because there is nowhere else left to write it.

The cost is that spring-web is now a dependency of the contract. A consumer that is not a Spring application carries a jar of annotations it will not use, and a contract that declares its operations in one framework's vocabulary has married that framework. I took the trade because the alternative was the same path typed twice, and the series has spent fourteen chapters on what happens to two descriptions of one thing.


Four operations, three types

The CRUD operations are declared once, for every resource that has them.

public interface CrudRestService<NewDto extends AbstractDto, UpdateDto extends AbstractDto, Dto extends AbstractEntityDto> {
Enter fullscreen mode Exit fullscreen mode

Three type parameters rather than one, and that is the whole point of the interface. Creating, updating and reading are three shapes: a caller supplies neither identifier nor version when creating, supplies a version but not an identifier when updating, and receives both when reading. One type across all three would need a paragraph of prose explaining which field applies when, and prose is the part of a contract a generated client cannot check.

ProductsRestService extends it with the three product types and adds what is specific: the owner's listing, and a status change that is an operation rather than a field, for the reason the service layer gave when it chose changeStatus() over a setter.

Whether a generator resolves those type variables to real schemas or gives up and writes object is not something to assume. It is the first thing the test asserts.


Five parameters, one argument

A listing takes a page, a size, a sort field, a direction and an optional filter. As five parameters on a method, they travel as five arguments through every layer that carries them.

@GetMapping
ProductsDescriptionsDto getProducts(@ModelAttribute ProductSearchParametersDto parameters);
Enter fullscreen mode Exit fullscreen mode

Spring fills the object from the query string, and springdoc flattens it back into five separate query parameters in the document. The client sees exactly what it saw before, what changes is every signature between here and the database.

The defaults live in the object rather than in the caller, which is a small decision with a visible consequence. A request for a listing with no arguments is reasonable, and answering it with a 400 teaches clients to send boilerplate. Because the defaults are real, they belong in the published document too, which is why each one is declared rather than merely initialised:

@Parameter(description = "The requested page index. The first page is 1.",
        schema = @Schema(defaultValue = "1"))
private Integer page = 1;
Enter fullscreen mode Exit fullscreen mode

The flattening is the kind of behaviour that works until a library upgrade changes its mind, and the failure is quiet: a client generator would start asking callers to build an object and send it as one value, which is not what the server reads. There is a test for it.


A parameter with no argument

Two headers belong to the secured operations. One says who is asking, the other says which version of the row the caller was looking at when it decided to change it. Both were method arguments until this week, and on the four CRUD operations that meant the same two parameters, with the same two descriptions, repeated on every signature that needed them.

They are gone from the signatures now. The caller's identity belongs to the request, not to the argument list, and a precondition on a request is not data the method was sent. Where exactly each one is read is the next chapter's problem, and the contract has no opinion about it. What the contract cannot do is stay silent about them, because a required header that is absent from the specification is an API that works only for people who were told. So they have to be described without a parameter to hang on, and the two of them turned out to need different answers.

If-Match applies to two operations out of six, because only an update and a status change have a row whose version matters. It is declared where it applies:

@Parameter(name = IF_MATCH, in = ParameterIn.HEADER, required = true,
        description = "The version of the entity the caller read, as returned in its 'version' field.",
        schema = @Schema(type = "integer", format = "int32"))
Enter fullscreen mode Exit fullscreen mode

The caller's identification applies to all six, which makes it a property of the secured surface rather than of any operation on it. Declaring it six times is the shape of problem this chapter already rejected once, when the price field was being repaired by hand. So it is declared nowhere and added everywhere:

@Bean
OperationCustomizer requesterIdentification() {
    final var requester = new HeaderParameter()
            .name(HeaderConstants.REQUESTER_ID)
            .required(true)
            .description("The caller's identification.")
            .schema(new StringSchema().format("uuid"));
    return (operation, handlerMethod) -> SecuredRestService.class.isAssignableFrom(handlerMethod.getBeanType())
            ? operation.addParametersItem(requester)
            : operation;
}
Enter fullscreen mode Exit fullscreen mode

Which operations get it is decided by a marker interface the secured contracts implement, rather than by a package name. The customizer is handed the stub class, and the stub implements whatever its contract implements, so a contract that declares itself secured is one the generator can recognise without comparing strings. A package name would have worked today and broken silently the first time somebody moved a file.

This is the first place in these two chapters where the document asserts something no interface declares. Everywhere else the generator reads a Spring binding and reports what it found, and a wrong answer would mean the service and its description disagree about code that exists in one file. Here the location, the requiredness and the type are literals, and nothing compiles them against the thing that will eventually read the header. I took that over the alternative, which was keeping two arguments on every method so that a documentation tool could see them. A generator is not a reason to shape a signature.

One thing does survive the move. The header's name is not a string in either place, it is HeaderConstants.REQUESTER_ID, which is the same constant the service will read it by, so the one piece of this that a typo could break quietly is still written down once. That class exists for exactly the reason the paths do.

There is a hole left in this, and it is worth naming rather than discovering later. Nothing yet stops somebody adding a secured contract that forgets the marker. The operations would be documented, the document would look complete, and the header would be missing from exactly the operations that require it. The fix belongs next to the mapping guard a few lines below, and it is the same fix: a contract under the secured package that does not declare itself secured should fail the build rather than produce a plausible document.


An application with nothing in it

What makes the rest of it possible is a Spring Boot application in the contract repository that contains no services, no database, no configuration of its own, and no controllers.

@SpringBootConfiguration(proxyBeanMethods = false)
@EnableAutoConfiguration
public class DocumentationApplication {

    static void main(String[] args) {
        SpringApplication.run(DocumentationApplication.class, args);
    }
Enter fullscreen mode Exit fullscreen mode

Two details in four lines. @SpringBootConfiguration with @EnableAutoConfiguration rather than @SpringBootApplication, because the third thing that annotation brings is a component scan and there is nothing here to scan. And main is not public, which Java has allowed since 25 and which this project has been doing since the services lost their public entry points.

What the application needs are controllers, and controllers are what does not exist. So it makes them:

final var controller = new ByteBuddy().subclass(Object.class).implement(contract)
        .name("com.pe.advanced.api.openapi.generated." + contract.getSimpleName() + "Controller")
        .annotateType(AnnotationDescription.Builder.ofType(RestController.class).build())
        .method(isAbstract()).intercept(StubMethod.INSTANCE)
        .make().load(DocumentationApplication.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
registry.registerBeanDefinition(contract.getSimpleName(), new RootBeanDefinition(controller));
Enter fullscreen mode Exit fullscreen mode

A scanner finds every interface under com.pe.advanced.api.rest carrying a @RequestMapping. For each one, ByteBuddy builds a class that implements it, annotates that class @RestController, and gives every abstract method a body that does nothing at all. The result is registered as a bean definition. Spring then sees what it always sees - a controller with mappings - and springdoc sees real handler methods to describe.

Every one of those endpoints returns null to anybody who calls it, and nothing calls them. The application exists to be read.

One line in that loop is not about generating anything:

if (AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class) == null) {
    throw new IllegalStateException("Missing HTTP mapping on " + method);
}
Enter fullscreen mode Exit fullscreen mode

A method on a contract interface without a mapping is not a documentation problem, it is an operation that no client can call and that nobody will notice is missing, because an absent operation leaves no trace in a generated file. This turns it into a failed build. The same instinct appears a few lines above it, where finding no contracts at all throws rather than producing an empty document, which is what a renamed package would otherwise do silently.


Why not write the controllers by hand

The simpler version of this is two small classes that implement the two contracts and return null, annotated @RestController, committed to the repository.

It works, and it has one failure mode that is enough to reject it. The classes are a parallel structure that has to be kept in step with the interfaces by whoever remembers, and the day somebody adds a third contract and forgets the third stub, nothing fails. The build succeeds, the document is produced, and it is missing an operation. A specification that is silently incomplete is worse than one that is absent, because the frontend will build against it and discover the gap at integration time.

The generated version cannot drift, because there is nothing to keep in step: the stubs do not exist until the scan finds a contract, and the scan finds every contract. That is the same argument the application module made in Chapter 13 for listing beans by hand - except that there the explicit list was the safer choice and here the generated one is, and the difference is which of the two can fail loudly.

ByteBuddy is a dependency most projects would rather not have, and this one does not carry it anywhere it matters. The module declares maven.install.skip and maven.deploy.skip, so nothing it produces reaches a repository and no consumer inherits anything from it. It is a build-time tool that happens to be written in Java.


A build that starts a server to read it

The Maven side is mechanical, and two parts of it are worth copying.

The spring-boot-maven-plugin starts the application at prepare-package and stops it at package. In between, springdoc-openapi-maven-plugin fetches /v3/api-docs and /v3/api-docs.yaml and writes both to disk. The ports come from build-helper-maven-plugin, which reserves two free ones at initialize - one for HTTP and one for the plugin's JMX channel - because a fixed port is a build that fails on a developer's machine for a reason that has nothing to do with the code.

A random port creates a problem of its own, and this is the line that solves it:

return new OpenAPI().info(new Info().title("Advanced Spring API").version(version))
        .servers(List.of(new Server().url("/")));
Enter fullscreen mode Exit fullscreen mode

Without it, springdoc records the server it was read from, and the published document tells every consumer that the API lives at http://127.0.0.1:49731. It would be correct for about four seconds.

The Swagger UI is unpacked from the webjar that springdoc already depends on, rather than pinned at a version of its own. That is one less version to keep in step, and the only file replaced is swagger-initializer.js, which otherwise points at the Petstore demo. What ships is a directory containing the UI and the two documents, which opens from a file system, a static host, or a raw repository, with nothing to install.

Where it goes after that is the part I would not copy without thinking. Mine lands in a Nexus raw repository, under a path and the contract's version, uploaded by wagon-maven-plugin at deploy. That is infrastructure I happen to have. The portable part is everything before it: a directory produced by the build, versioned with the contract that produced it.


Telling the document what the mapper does

A specification can say that a price is a string. Only a mapper makes it one, and the two are written in different places by different mechanisms, which is the condition under which they disagree.

SpringDocUtils.getConfig().replaceWithClass(BigDecimal.class, String.class);
Enter fullscreen mode Exit fullscreen mode

The previous chapter decided that money leaves this API as a string. The generator knows nothing about that decision - it reads Java types, finds BigDecimal, and calls it a number. The per-field repair is @Schema(type = "string") on every money field, which is an agreement maintained by whoever remembers.

I know what that costs, because I have the version where it was maintained by hand, and three fields had been forgotten. The published document described them as numbers while the service sent strings, and nothing anywhere would have caught it: the schema was plausible, the serialization was correct, and the two were never compared.

One line in the documentation application is the whole fix. The annotation disappears from every field, and the question of whether somebody remembered stops existing.


What the tests prove

There are thirteen tests against the generated files, and they run after the server has stopped, against what is on disk rather than what an endpoint says. They exist because a generated document is the most plausible wrong answer a build can produce. It is made by a tool reading annotations, and a tool reading annotations is the thing that emits something reasonable when one is missing. Nothing about the file looks wrong when an operation is absent from it.

So the tests check the things that could silently stop being true. That both projections are still two schemas rather than one, and that the public one carries no version. That CrudRestService resolved to NewProductDto and UpdateProductDto rather than to object. That every failure is a ProblemDetail under application/problem+json, which is what the service actually returns. That both headers are in the document as headers, which is the one pair of claims here that rests on a declaration and a customizer rather than on a binding, and that the anonymous operations carry neither. That no operation declares the same parameter twice, which is what two mechanisms writing into one list can produce. That the search parameters are five query parameters and not one schema. That no property is a number without a format, which is how a decimal that escaped the string conversion announces itself. And that servers[0].url is /.

One assertion is deliberately absent. There is no check on the number of operations, because a count has to be updated by hand on every change to the API, and the third time somebody updates it without reading it, the test has finished teaching them to ignore it.


What this part settled

The specification exists. It is produced by a build, from the same interfaces the service will implement, with its own version and no running service anywhere in the process. It can be opened in a browser, fed to a client generator, or pointed at by a mock server, and it describes every operation this API will have before a single one of them answers a request.

That is the argument these two chapters have been making. The contract is a build artifact, so the only thing it can describe is what the interfaces declare, which is what separates it from a document somebody writes alongside the code and updates when they remember.

What it cannot do is answer anything. Every operation in that document is backed by a class that was generated to return null, and the service in the other repository still has no controllers at all.


What's Next?

Chapter 17 implements them, and most of the work is already decided. A controller implements its interface and inherits the mapping, the path and the parameter binding, so what is left in each method is the part that was always the point: calling a service and returning what it gives back.

Three things that have been open for several chapters close there. The optimistic lock from Chapter 14 produces an exception the handler does not catch, and until it does, a conflict is a 500. The version has to travel from the request to the entity, which is what If-Match is for. And the security rule has to deny by default and name what is public, rather than leaving a prefix to carry a meaning that nothing enforces.

The first @WebMvcTest also lands there, which will finally answer a question left open in Part 1 of Chapter 13: whether declaring @ComponentScan by hand costs the filters that slice tests rely on.


Codebase & Architecture Blueprint

The entire evolutionary architecture of this project is tracked using strict Git tags. There are two repositories: the service, and the API contract it implements. This chapter, like the previous one, is entirely in the second one.

Two chapters now without a commit in the service, which is the separation doing what it was supposed to do: a specification the frontend can build against was produced without touching the application at all.

Note: All core modules are configured with strict compilation-level boundaries. Compile and run mvn clean install to see the structure in action. Maven version 3.9.* and Java 25 are required.

◀️ Read Chapter 15: The Contract Ships Before the Server Does
▶️ Read Chapter 17: Implementing the Controllers (Coming soon)


Join the Masterclass Journey

This article is part of an ongoing weekly series. If you want to receive every upcoming chapter directly in your inbox, alongside deep-dives, infrastructure architecture diagrams, and premium insights before anyone else, subscribe to my Substack Newsletter here!


Recommended Resources for Java & Spring Boot Engineers

Disclosure: I earn a commission if you purchase through the links below, at no additional cost to you.

If you are preparing for Senior/Lead Java interviews or looking to solidify your Spring Boot & Architecture skills, check out these highly-rated resources from the Javarevisited publication (Use promo code friends20 for an exclusive 20% discount automatically applied at checkout):

Top comments (0)