Generating client code from an OpenAPI specification can save a lot of development time and reduce risk of that code being outdated. However, it is not immediately obvious how to generate that code from a Spring Boot application. This article explains how to generate Angular code from a Java Spring Boot project using Springdoc Swagger and Maven (though you can easily swap out Angular for any other language).
One of Swagger’s strongest selling points is the ability to generate client code from an OpenAPI specification – this usually works well if you’re using the Design First approach. Unfortunately, there doesn’t seem to be much information on how to automate the process when using the Code First approach. Today we will learn how to easily generate Angular code from a Java Spring Boot project using Springfox Swagger and Swagger Codegen.
If you’re using the springfox-swagger2 library, you might come across a problem when it comes to generic types (such as Pet<T>). In cases where diamond brackets are used, Swagger will generate an invalid specification, resulting in a validation error in the Swagger Editor (“”$ref values must be RFC3986-compliant percent-encoded URIs”).
By default, Spring Boot uses an OpenEntityManagerInViewInterceptor which “binds a JPA EntityManager to the thread for the entire processing of the request […] to allow for lazy loading in web views despite the original transactions already being completed”.
In other words, in every
@RestController action, instead of throwing a
LazyInitializationException when you forget to fetch a lazy-loaded property, Spring will now fetch the property outside of the original transaction. The pattern (or antipattern) is called Open Session In View (OSIV) and, while it sounds fairly useful, is not a good choice for production environments.
Spring Boot, by default, uses Thymeleaf 2 as its template engine. You can, however, make it use the newer version.