Spring Boot with Swagger Generated Code Raw Notes - technoangel/java GitHub Wiki
This is a summary of the things I didn't understand by running a Swagger Spring Server Stub command in *nix and referring to the main, the controller, and the model.
swagger-codegen generate -i server/swagger-contract.yml -l spring -o springboot-endpoints
and following with
java -jar target/swagger-spring-1.0.0.jar
@SpringBootApplication is a macro for @Configuration, @EnableAutoConfiguration, and @ComponentScan. It was rolled up because of how common these three annotations were used in Spring applications.
You can still override, say, @ComponentScan, by including a subsequent declaration underneath
@SpringBootApplication
@ComponentScan(basePackages = {"package_1", "package_2"})This is an interface for drawing command-line options into your Spring application. It is a functional interface with the single #run method to be overridden.
public class MyProject implements CommandLineRunner {
@Override
public void run(String... arg0) throws Exception {
...
}
}This is the main Spring executor, taking your SpringBootApplication and issuing containers and bootstrapping your project
public class MyProject implements CommandLineRunner {
@Override
public void run(String... arg0) throws Exception {
...
}
public static void main(String[] args) throws Exception {
new SpringApplication(MyProject.class).run(args);
}
}Jackson is a library to handle xml and JSON. It provides good ways to de/serialize objects, read files, etc.
The Jackson ObjectMapper is used specifically to de/serialize objects to/from JSON.
final ObjectMapper mapper = new ObjectMapper();
MyValue value = new MyValue();
File newState = new File("my-stuff.json");
mapper.writeValue(newState, value); // writes JSON serialization of MyValue instance.
MyValue older = mapper.readValue(new File("my-older-stuff.json"), MyValue.class);@Controller is a @Component and is used on a class for autodetection that the class will handle some Spring web requests. Typically used in combination with @RequestMapping annoations on some of the class methods to identify which requests will be handled.
@Controller
public class MyProjectController implements ProjectApi {
...
}This creates or appends a new logger to the project registered with the class given in the argument.
public class MyProject {
private static final Logger log = LoggerFactory.getLogger(MyProject.name);
}When a request is handled by the DispatcherServlet and handed off to the correct controller, the request information is put into a HttpServletRequest object. This object should be passed into the controller constructor.
@Controller
public class MyProjectController {
HttpServletRequest request;
@Autowired
public MyProjectController(HttpServletRequest request) {
this.request = request;
}
}Literally, this is an extention of HttpEntity with an added HttpStatus, but that's not really useful. It is the return type for a @Controller method
@Controller
public class MyProjectController {
...
@RequestMapping("/handle")
public ResponseEntity<String> handle() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue");
return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}
}Two flavors: Spring Annotations that instruct on the creation and wiring of the application, and Swagger annotations that instruct about the nature of the expected API handshaking.
This is not a Swagger annotation, but a Spring one. This makes sure the object being passed in are valid. Here is a more illustrative example:
@RequestMapping(value = "/appointments", method = RequestMethod.POST)
public String add(@Valid AppointmentForm form, BindingResult result) {
...
}
static class AppointmentForm {
@NotNull @Future
private Date date;
}This is also a Spring annotation and not a Swagger one. This says to pull the parameter out of the request body (as opposed to the path). The @PathVariable is part of the URI and not optional (if it were optional, it would change the URI and be handled by a different request mapper).
@RequestMapping(value="/user/{userId}/invoices", method = RequestMethod.GET)
public List<Invoice> listUsersInvoices(
@PathVariable("userId") int user,
@RequestParam(value = "date", required = false) Date dateOrNull) {
...
}@JsonProperty is a Spring annotation to declare the key for the assocated property value if serialized into JSON.
@JsonProperty("Msg")
private String message = null; // would produce { Msg: null } in JSONThis is a description/validation of the parameter that the parameter cannot have a null value.
Example Swagger RequestMapping method (for reference):
public ResponseEntity<String> endpoint(@NotNull @ApiParam(value = "value description", required = true) @Valid @RequestParam(value = "id", required = true) String identity)This is a description of the parameter ("Narrating the parameter") and also describes whether it is mandatory.
This is a Swagger annotation that identifies the request mapping and helps Swagger scan for controller/action operations in the application. It has arguments for #value and #description
@Api(value = "endpoint", description = "the endpoint API")@ApiOperation is the Swagger annotation for marking up a particular action in an @Api-identified controller (or controller interface). @ApiOperation includes a brief description (value), a long description (notes), the return type (response), and the wrapper type (responseContainer) if a collection of the return type is what is required (like a blind, indexing GET request).
@ApiOperation(value = "Finds Pets by status",
notes = "Multiple status values can be provided with comma seperated strings",
response = Pet.class,
responseContainer = "List")
public Response findPetsByStatus(...) { ... }This is a Swagger annotation that identifies how return codes are processed. The list (@ApiResponses) is a collection of each return code and expected response type.
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success", response = EndpointResponse.class),
@ApiResponse(code = 400, message = "Bad request - missing parameters.", response = ErrorResponse.class),
@ApiResponse(code = 401, message = "Authorization information is missing or invalid.", response = ErrorResponse.class),
@ApiResponse(code = 404, message = "Bad request - no system can respond.", response = ErrorResponse.class),
@ApiResponse(code = 200, message = "Error", response = ErrorResponse.class) })@ApiModelProperty is a Swagger annotation that details the parameters of a model, just as permissible values or details about the property.
@ApiModelProperty(value = "pet status in the store", allowableValues = "available,pending,sold")
public String getStatus() {
return status;
}