TIL: Spring Boot, pt2
Spent more time this evening going through the Spring Boot tutorial I had linked last night. Didn’t get as far as I liked, but the coverage so far has been pretty great. I feel like the instructor is doing a good job of explaining why we’re doing what we’re doing, and isn’t afraid to mention that most things are just behind the scenes magic.
Anyways, today is going to be another day full of notes! Yay!
Setting up the project
- Create a new package (not just a class) inside of the
src/main/javadirectory, and then place the new class file inside of it
- Inside of that new class file, we’ll add our main statement for the application, and add on special annotation to tell spring how to treat it
- In order to setup the application to run, we’ll use the
SpringApplication.runmethod. This takes in two different arguments: the first is the name of the class where the main resides (ends with a .class), and the second is any other args, such as the args passed to main:
- That is all it takes to make an application (though it doesn’t do anything)
But How did that work?
- SpringApplication is a static class that has a static method called run
- Run takes in a class that has the spring annotation
- With this parameter, it’s setting up the default configuration behind the scenes
- Starts up a Spring application context (basically a container for everything to run in)
- Performs a classpath scan looking for all of the annotations on each of the classes found
- Will treat the classes differently based on whatever that annotation is
- Will scan through all of the files in the classpath looking for the annotations
- Finally, starts up a Tomcat server (java server instance)
Adding in a Controller
- Just another Java class that will handle our routes (controller)
- Mark it with annotations to tell spring that it is a controller
- Will contain our route information
- Leverages Spring MVC
- Create a simple new java class an annotate it with
@RestControllerwitch will create the controller
- Can take it a step further and define the path in the annotation for which the method will execute:
- This maps to every method. If you want to limit what’s used, you must specify specifically what you want to support.
- That’s all that’s needed. This will get picked up when executed (picked up during the scan)