How to get started with the Spring Framework
Using Spring can supercharge your Java application development. Here's how you can use it to build robust, scalable applications with less effort.
Sep 19, 2023 • 7 Minute Read
“What’s the Spring Framework?” you find yourself asking. With its sixth major release, there are a great many engineers who've already embraced it. Some individuals and entrepreneurs have entire careers and businesses nestled inside its community.
But if you are one of the lucky 10,000 to start your journey with it today, you’re in for a treat. In this article, we'll explore why and how to start with Spring and dive into its latest and most useful features.
The power of Spring
In the world of software development, frameworks play a pivotal role in simplifying complex tasks, boosting productivity, and enhancing the overall quality of applications. The Spring Framework, often referred to as Spring, stands as the gold standard of a Java-based framework and has captured the allegiance of developers worldwide. With its latest release, Spring Framework 6.0, the journey becomes even more enticing for newcomers, promising a delightful experience filled with simplicity, flexibility, and innovation.
Embracing the Spring philosophy
Let's first take a moment to understand what Spring is all about. At its core, Spring is an open-source framework for building robust and scalable Java applications. It doesn't just provide a set of tools and libraries; it embodies a comprehensive philosophy that encourages best practices, modularity, and testability.
Spring is designed to simplify the development process by abstracting many of the complexities associated with enterprise application development. It encourages the use of programming paradigms like inversion of control (IoC) and dependency injection, which help manage object dependencies and improve code maintainability.
Let’s see a core example of this philosophy in action. Take a typical class, unenhanced by Spring:
```java
class OrderController {
final OrderRepository orders = new JdbcOrderRepository();
Order findOrder(String id) { … }
}
```
This class is not as resilient to change as it could be since it inlines its dependency on “JdbcOrderRepository.”
Organize your class like this instead:
```java
class OrderController {
final OrderRepository orders;
OrderController(OrderRepository orders) {
this.orders = orders;
}
Order findOrder(String id) { … }
```
And you’ll allow Spring to construct “OrderService” for you and inject the dependency on your behalf. Now this class is dependent on just the “OrderRepository” interface, not the specific implementation.
Spring is about making it easy to make the right architectural and design decisions, and encouraging dependency injection is just one of many. As you can see, though, it takes doing it “the Spring way” to extract the full benefit.
Exploring the Spring landscape
Spring's journey doesn't stop at design patterns like inversion of control and aspect-oriented programming (AOP). It’s evolved into a powerful framework facilitating various architectural paradigms, while helping you focus on your engineering core competencies and business logic.
Spring is commonly used to enable paradigms like microservices, serverless, real-time streaming, and cloud-readiness. Let’s take a closer look at one of these: building out a microservice architecture.
You can use Spring Web MVC to model the RESTful endpoints; Spring Data JDBC to model the underlying resources; and Spring Security to secure the microservice with JWT. You can also use Spring buildpacks to dockerize each microservice for easy Kubernetes deployment and turn it into a native application for millisecond-level startup.
Architectural paradigms
Consider, for example, a complete Spring RESTful application listed here:
```java
@RestController
class OrderController {
OrderRepository orders;
OrderController(OrderRepository orders) {
this.orders = orders;
}
@GetMapping("/order/{id}")
ResponseEntity<Order> findOrder(@PathVariable("id") String id) {
return orders.findById(id).map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
}
record Order(@Id String id, String username) {}
@Repository
interface OrderRepository extends CrudRepository<Order, String> {}
@SpringBootApplication
public class SimpleApplication {
@Bean
UserDetailsService users() {
return new InMemoryUserDetailsManager(User.withUsername(“user”)
.password(“{noop}password”).authorities(“order:read”).build());
}
public static void main(String[] args) {
SpringApplication.run(SimpleApplication.class, args);
}
}
```
The above application has the following high-level characteristics:
Deploys an HTTP microservice that listens on port 8080
Responds to requests like http://localhost:8080/order/123 in standard JSON
Secures each request with HTTP Basic
Connects to an order database (in-memory by default) and formulates the appropriate SQL query for each request
Not bad for less than 40 lines of code.
Core competencies and business logic
It does all this while helping you stay focused on the business logic of your code.
Take a look at Spring Security, my favorite Spring module. Did you see how security was automatic in the above application? But let’s say your needs are more sophisticated, and you need that order endpoint to be invoked only by users with the order:read permission.
Change this:
```java
@SpringBootApplication
@EnableMethodSecurity
public class SimpleApplication {
…
}
```
and this:
```java
@GetMapping
@PreAuthorize(“hasAuthority(‘order:read’)”)
Order findOrder(@PathParam(“id”) String id) { … }
```
and now only users with that permission can call that endpoint.
Spring’s declarative model allows you to focus on what you want the code to do, while letting Spring determine how to do it.
Embarking on your Spring journey
Embarking on your Spring journey may seem daunting given its size and reach.
Begin by visiting start.spring.io, a platform to declare your application's modules and dependencies, setting you on the right path.
Use it to build a simple REST API. If you want to use the above OrderController snippet, select Spring MVC, Spring Security, Spring Data JPA, and H2 as the modules that you want. Then use that snippet as your main class.
Leverage learning platforms like Spring Guides, Spring Academy, Baeldung, or Pluralsight Skills to learn and master Spring's intricacies. Each offers a unique approach—structured learning or free-form exploration—tailored to your preferences.
Engage with the Spring community. The Spring team diligently monitors platforms like StackOverflow and GitHub, ready to assist with questions and bugs. You can also attend the annual SpringOne conference, where you can interact with fellow enthusiasts and the Spring team, propelling you toward Spring expertise.
Cutting-edge coding with Spring
But will Spring keep you on the cutting edge? Worry not, Spring is keeping pace with innovation. Spring Framework 6.0 demonstrates its agility through a lineup of cutting-edge features:
1. Java 17 Support
Spring Framework 6.0 is fully aligned with the latest advancements in the Java ecosystem. This release embraces Java 17, allowing developers to leverage long-anticipated language features, like records and pattern matching, and performance enhancements, like improved garbage collection.
2. Kotlin compatibility
Kotlin, a popular programming language for the JVM, enjoys enhanced compatibility with Spring Framework 6.0. Developers can now harness the power of Kotlin's concise and expressive syntax while seamlessly integrating with Spring components.
3. Observability and metrics
In the 6.0 release, new traces, metrics, and logs are found in each module. This enables you to zero in on performance issues, understand the flow of requests, and analyze and respond more quickly to incidents. Each of these will effectively lower your mean time to resolution.
4. Native support
Now you can easily move your application from a .jar that requires an installed JDK to an application that runs natively on its operating system. This makes for lightning-fast startups and dramatically smaller memory and filesystem footprints, decreasing operational overhead and increasing customer satisfaction.
You can read more about GraalVM, the JDK that compiles to native applications in my article Top Java trends of 2023.
Spring's vitality remains resolute, propelling your coding endeavors toward unprecedented heights.
Conclusion
In this article, we embarked on a journey through Spring, a Java framework renowned for building scalable, modular applications. Learning Spring idioms empowers you to craft code that excels in performance, longevity, and readability. Spring's evolution is far from over; its recent updates align with the latest Java version and introduce heightened support for Kotlin, observability, and native compilation.
How to kickstart your Spring venture
Pluralsight also offers a wide range of Java and Spring related courses (including some authored by yours truly) that cater to your skill level. You can sign up for a 10-day free trial with no commitments.
If you’re looking to get started with Spring, the best place to start is with the Spring Framework: Core Spring learning path. There are courses for beginner, intermediate, and advanced Spring users — just pick the starting point that works for you. If you’re not sure where you’re at, that page has a skill assessment you can use that will recommend where you should start out.
If you’re interested in securing Spring Data REST APIs, I’ve got a dedicated course you can check out, as well as the following ones on Java:
The path to becoming a Spring expert awaits—take the first step today!