Table of Contents
Background
- What is Spring?
- Backend web framework for Java.
- Used to build APIs and web services (monolithic or microservices).
- What is Spring Boot?
- Wrapper around Spring. Has everything from Spring + additional features.
- Simplifies Spring using annotations for autoconfiguration.
- Advantages of Spring Boot?
- Most of the configuration is handled for you under the hood.
- Just have to provide dependency configurations in properties files + annotations in code
- Embedded HTTP server (Jetty or Tomcat).
- No need to setup an external web server like nginx. Just run the application and a server will be created in your IDE.
- Embedded db (H2) for easy testing
- Actuators to check service health and status.
- Disadvantages - Opinionated framework, makes you follow preset architecture rules.
Spring Components and Scanning
- Every item that’s part of the internal structure of your app is a Spring component.
- You can mark items as Spring components with annotations
@Component
, @Service
, @Repository
, @RestController
are class-level annotations that mark a class as a Spring component and adds them to the Spring context.
@Bean
is a method-level annotation that adds a method to the Spring context.
- Spring Boot will scan your code for components and use them.
@SpringBootApplication
- Added over the PSVM method of every Spring Boot app.
- When the app is initialized, Spring Boot scans all classes in the current package containing the PSVM file. Then use them to configure the app.
- To scan other Spring Boot projects outside the current application and use their components, you need to scan them manually:
- Add outside projects you want to include as Maven/Grade dependencies.
- Add
@ComponentScan('package.name')
under @SpringBootApplication
- Note: Different SB projects can have the same package names.
Dependency Injection
- What is dependency injection?
- DI is a design pattern for Java classes, where you inject the class’s dependencies directly into them instead of manually assigning an object in the constructor
- Makes it easier to unit test, by isolating the tested class from all of its dependencies.
- How to do DI
- Declare your dependency class as a field object, but don’t assign it.
- Add
@Autowired
above constructor, so Spring will implicitly handle importing dependencies.
- In your class’s constructor, do
this.field = myDependency;
- When to use DI
- DI is crucial to the way all Spring applications are developed.
- Use it whenever you have an external component (one that you built yourself, or imported from a library) that you want to use in the current class.
Supplemental Tools
- Spring Tool Suite
- A set of tools added onto your IDE, to help build spring apps.
- Supports VS Code and Eclipse