Pro Spring Boot 3 with Kotlin: In-Depth Guide to Best Practices for Cloud-Native and Microservices Development - podcast episode cover

Pro Spring Boot 3 with Kotlin: In-Depth Guide to Best Practices for Cloud-Native and Microservices Development

Jan 28, 202641 min
--:--
--:--
Download Metacast podcast app
Listen to this episode in Metacast mobile app
Don't just listen to podcasts. Learn from them with transcripts, summaries, and chapters for every episode. Skim, search, and bookmark insights. Learn more

Episode description

Focusing on best practices for developing various applications. It covers fundamental Spring Boot concepts such as auto-configuration, dependency management (Gradle), and application properties, demonstrating their usage in web development, data access (SQL, JPA, MongoDB, Redis), and reactive programming. The text also explores advanced topics including Spring Security (OAuth2), messaging with JMS and AMQP (RabbitMQ), Spring Boot Actuator for monitoring and observability (metrics, logs, tracing), and native image generation with GraalVM. Finally, it introduces Spring Cloud for microservices (Consul, Vault, OpenFeign, Kubernetes), custom Spring Boot starters, Spring Modulith for modular applications, Spring AI, and Spring for GraphQL, offering comprehensive insights into modern application development with Spring Boot.

You can listen and download our episodes for free on more than 10 different platforms:
https://linktr.ee/cyber_security_summary

Get the Book now from Amazon:
https://www.amazon.com/Spring-Boot-Kotlin-Depth-Microservices/dp/B0DJGGPMRT?&linkCode=ll1&tag=cvthunderx-20&linkId=9116bd10a0f81d3bc2b9d9013c3bc1b0&language=en_US&ref_=as_li_ss_tl

Discover our free courses in tech and cybersecurity, Start learning today:
https://linktr.ee/cybercode_academy

Transcript

Speaker 1

Building modern software applications today. Wow, it often feels like you're trying to navigate this this vast, ever expanding ocean, doesn't it.

Speaker 2

It really does. Frameworks, patterns, deployment strategies.

Speaker 1

Yeah, the sheer volume can be overwhelming if you're trying to stay informed and you know, build genuinely robust system.

Speaker 2

Absolutely, the landscape just shifts constantly, trying to keep up with every single new thing.

Speaker 1

It's well, it leads to information overload pretty fast.

Speaker 2

Right, which is why having a guide, some kind of compass is just so.

Speaker 1

Crucial exactly to cut through all the noise.

Speaker 2

And that's exactly what we're bringing you today. We're diving headfirst into the core of modern application development. We're pulling out the really important nuggets from pro spring Boot three with Cotlin, And this isn't just about code, right, It's about understanding the why and the how behind these powerful tools that honestly make a lot of the Internet just work.

Speaker 1

And what's great here the source material comes from real experts, Peter Spieth and Felid Gutierra and Febe brings insights straight from VM where you know, the folks who actually create spring boot. Wow. Okay, so straight from the.

Speaker 2

Source, pretty much distilled down for clarity.

Speaker 1

So our mission for this deep dive is really to unpack how spring Boot, especially with Cotlin, takes these inherently complex software development tasks and just simplifies them, radically simplifies them.

Speaker 2

Yeah, show how it delivers these like surprising features right out of the box.

Speaker 1

Exactly and helps developers like you build apps that are fast, secure and crucially observable and ready for the.

Speaker 2

Cloud get ready for some aha moments. I think it can really shift how you view building apps.

Speaker 1

Think of this as your shortcut. We're cutting through the jargon, getting straight to what's genuinely important.

Speaker 2

And how you can actually apply to your own work right pretty much immediately.

Speaker 1

Okay, let's start with Springboot's core promise, then simplification and opinionation. So why spring Boot. The book makes it clear it's designed ground to be enterprise ready.

Speaker 2

Right with best practices just applied automatically.

Speaker 1

And that's the key.

Speaker 2

That's the key. The biggest advantage honestly, and it's a game changer for productivity, is that opinionated nature, meaning it.

Speaker 1

Makes choices for you sensible defaults.

Speaker 2

Exactly, sensible defaults, yeah, which leads to what the authors call sometimes zero configuration.

Speaker 1

Zero configuration. Okay, that sounds almost too good to be true. How much pain does that actually save?

Speaker 2

Well, think about the old days, right, all that XML or just tons of Java configu code just to get a basic web app talking to a database.

Speaker 1

Oh yeah, hours, sometimes days.

Speaker 2

Spring boots autoconfiguration isn't just convenient, it's like the whole paradigm shift. It means you can focus on your actual business logic, like from day.

Speaker 1

One, trusting the framework to wire up most of the infrastructure.

Speaker 2

Yeah, like ninety percent of it intelligently. It frees you from that boiler plate, letting you build complex stuff without getting bogged down and repetitive setup.

Speaker 1

That is a huge claim about productivity. But does that opinionated nature does it ever become a limitation? Do those defaults ever get in your way?

Speaker 2

It's a fair question. I mean, while it massively cuts down initial development time, sure there are times you need finer.

Speaker 1

Control, but you can override things.

Speaker 2

Oh yeah, absolutely. Springboot is designed to let you step in and override defaults pretty easily when you need to. Okay, and connecting this to the bigger picture, this whole approach also makes Springboot perfect for cloud native applications. It follows those twelve factor app principles right.

Speaker 1

The best practices for building scalable cloud.

Speaker 2

Apps exactly, things like dependency management, logging, config It handles that well. And it also sets you up for native images using AOT compilation with Grail VM.

Speaker 1

Which is huge for performance in the cloud. We'll definitely circle back to that, but let's stick into the magic a bit more. How does this autoconfiguration actually work? What happens when I run my app?

Speaker 2

So it all kicks off with the spring application class in Cotland. Your main method basically run this singleton, okay, but the real powerhouse, the thing you see everywhere is the at spring boot application.

Speaker 1

Annotation right, that one annotation, yeah.

Speaker 2

And it's actually an alias for three other critical ones You've got at spring boot configuration, which marks the class as a config source. At enable autoconfiguration, which is the trigger really. It starts the autoconfig based on what dependencies it finds on your class path.

Speaker 1

Ah, so it looks at my library exactly.

Speaker 2

And the third is that component scan which finds your own components, your controllers, services, that kind of thing.

Speaker 1

So if I just add, say the post Rascal driver dependency to my project. Yep, springboot sees that and just sets up a data source and maybe a transaction manager without me writing any code for it.

Speaker 2

That's precisely it. It sounds like a dream, but it works. It configures essentials, transaction manager for transactions, entity manager, factory if you're using JPA, the data source for connections, message converters for web stuff, even resource handler registry for static files.

Speaker 1

All that plumbing just handled, all.

Speaker 2

Handled without XML, without manual Java config beans most of the time.

Speaker 1

That's genuinely impressive. But what if I don't want one of those defaults. Say I have a really custom setup for web stuff, you can.

Speaker 2

Definitely control it that it enables autoconfiguration annotation, it has exclude and exclude name parameters. Ah okay, So if you didn't want the standard WEBNBC setup, you could just say exclude array of WEBMVC, autoconfiguration dot class. So you get the convenience, but you still have control.

Speaker 1

That's a good balance, okay. Shifting gears slightly. The book talks about personalizing your app beyond the core configuration. I was kind of amused by the custom banner thing.

Speaker 2

Yeah, it's a small touch, but it shows the level of detail instead of the default spring boot ask.

Speaker 1

Art, which is iconic but maybe not for every app.

Speaker 2

Right, you can just drop a banner dot txt file in src in main resources or set the spring dot banner dot location property.

Speaker 1

You can even use online generators right like patoorjk dot com.

Speaker 2

Yep makes something unique, or just turn it off completely with banner mode doff. It's simple but nice to have that option.

Speaker 1

So even the visual startup is configurable. What about passing arguments when you launch the app for different modes or environments?

Speaker 2

Spring good makes that super easy with the Application Arguments interface.

Speaker 1

Okay.

Speaker 2

Lets you easily grab both option arguments you know, things like enable or option value one exactly, and also non option arguments maybe like command words update or upgrade. Really useful for passing parameters at run time?

Speaker 1

And what about the app's life cycle? Are there hooks for running code at specific startup points?

Speaker 2

Yes, and there's a clear order. First, application runner gets called it gets those nice parsed application arguments. Then command line runner runs it gets the rostering arguments if you need those for some reason.

Speaker 1

The final signal the.

Speaker 2

Very last event signaling everything's initialized and ready to go. Is the application ready event? Understanding that sequence helps you plug in custom logic at the right time.

Speaker 1

That's a clear progression. Good to know. But once the app's running, how do we handle settings? You know, avoid hardcoding data based passwords everywhere. Let's get into configuration management.

Speaker 2

Okay, For basic single properties, you can just inject them using at value property.

Speaker 1

Name right, using that Spring expression language to an el exactly.

Speaker 2

Spitteel gives you a lot of power there. It pulls values straight from your application dot properties or application dot EML file.

Speaker 1

But what if I have a bunch of related settings, like all the connection details for some service, server, port, username, at value for each one seems messy?

Speaker 2

It would get messy fast. And that's where at configuration properties is fantastic. You can bind a whole group of properties like users, dot serve, dot server, users, dot service, dot port all into a single type safe class. Keeps things super clean and organized much better for maintainability.

Speaker 1

Nice And where did these properties actually come from? Is there a hierarchy? Like can an environment variable override something in my packaged application?

Speaker 2

Absolutely? And that's crue. Spring boot looks in multiple places application dot properties inside your jar first, then it looks for the same file outside the jar. Then environment variables, command line arguments, and the later ones win exactly. External sources always overwrite internal ones. So yes, an environment variable set in your deployment will trump a value inside the jar. Super useful for different environments.

Speaker 1

Takes total sense for cloud deployments and specifically for web apps. How does boot know whether to set up, for say, Tomcat, or for reactive netty.

Speaker 2

It smartly adapts based on your dependencies. If it sees Spring Bootstarter web, it assumes web application type servlet traditional blocking IO, usually with embedded Tomcat, okay. But if it find Spring Bootstarter web flux, it switches to web application type reactive, typically using Netty underneath for non blocking reactive handling.

Speaker 1

So it just figures it out based on what you include.

Speaker 2

GEP adapts seamlessly.

Speaker 1

Okay, that's flexible. Let's shift now to actually building things web development. First, classic question, at controller versus at rest control? What's the deal?

Speaker 2

Right? At rest controller is basically just a shortcut. It combines at controller with at response body.

Speaker 1

Okay, and what does that response body do? Again?

Speaker 2

It tells Spring that the return value of your method should be bound directly to the web response body, usually serialized as JSON by default.

Speaker 1

So at rest controller implies you're building an API that returns data like JSON.

Speaker 2

Exactly. If you used a plane at controller, you typically return like a view name for rendering HTML. If you wanted that controller to return JSON, you'd have to add at response body yourself. So for rest APIs at rest controller is almost always what you want.

Speaker 1

Got it that clears it up and static content HTML, CSS, JavaScript? Do I need a Patchy or Niekens in front Nope.

Speaker 2

Spring boot handles it automatically. It serves static content from standard locations in your class path, static public resources, or meta in free sources.

Speaker 1

So I just put my files there.

Speaker 2

Just put them there, and if you have an index dot html in one of those spots, boom, that's your home page. No extra config needed.

Speaker 1

Super handy. How about response formats like automatically getting JSON or maybe XML if a client asks for it.

Speaker 2

That's handled by HTPP message converters. Spring Boot sets these up for you. Jason works out of the box because the Jackson library is included with the webstarter and XML. If you add the Jackson XML extension dependency. Boot will automatically configure an XML converter two. Then it uses content negotiation based on the clients accept hitter to decide whether to send Jason or XML pretty.

Speaker 1

Smart okay, and can I tweak that Jason Serialization dates, for instance, can be formatted weirdly sometimes.

Speaker 2

Yep, easy fix. The default is a long ISO eight six oh one ish format, but you can change it globally with the spring dot Jackson dot datebomat property in application dot properties tailor it. However, you need.

Speaker 1

Good What about validating incoming data? Preventing bad data before it even hits my logic?

Speaker 2

Absolutely essential? Spring Boot integrates smoothly with the Jakarta validation API.

Speaker 1

So I can use annotation like at n blank exactly and not blank at not null at email at size, put them right on the fields of your request objects.

Speaker 2

If validation fails, spring Boot automatically handles it, usually returning a four hundred bad request with details. Keeps bad data out.

Speaker 1

And broader error handling. If something unexpected blows up deeper in my code, how do I give a clean error.

Speaker 2

Response for that? You use at controller advice along with at exception handler. This lets you centralize your exception handling logic.

Speaker 1

So one place to catch specific exceptions.

Speaker 2

Right, you can catch a custom retroboard not found exception for example, and format a nice consistent Jason error response across your whole API. Keeps your controllers cleaner.

Speaker 1

Okay, that makes sense. And mapping request to controller methods still the usual suspects like at get mapping, YEP at.

Speaker 2

Request mapping is the general one, but you'll mostly use the specifics at get mapping, at post mapping, at put mapping, at delete mapping. They map directly to the HDDP methods.

Speaker 1

And they support things like path variable.

Speaker 2

Oh yeah, pathvariables like email to pull values from the URL, plus flexibly use URL patterns using wild cards. You can also use response entity to have full control over the response, including headers like location.

Speaker 1

After creating something cool, okay, weblayer covered Now data Every app needs data persistence. How does boot simplify sl and no SQL databases? Let's start with SQL for SQL.

Speaker 2

The moment you add a database driver like the Postgres school one or do postgrisk, Correll, dot PRIs, aggressive, zeris growth counter Spring Boot auto configures.

Speaker 1

Things like the data source exactly.

Speaker 2

It sets up the data source and configures an efficient connection pool usually high CARICP by default without you doing anything.

Speaker 1

Wow, okay, no manual connection pool setup Nope.

Speaker 2

Saves a ton of boiler plate and ensures good performance right away.

Speaker 1

And what else does the framework offer for SQL?

Speaker 2

Well, the broader Spring framework gives you transaction management, so you can just annotate methods with at transactional and JDBC template, which massively simplifies raw JDBC code if you need to go that low level removes all that trycatch finally.

Speaker 1

Mess right the plan reduction again? What about setting up the database schema initially, especially for testing or local dev with embedded databases.

Speaker 2

Boot can auto initialize embedded databases like H two hsql derby. It looks for schema dot sql to create tables and data dot sql to populate them in your class path.

Speaker 1

Oh nice.

Speaker 2

It's even smart enough to look for platform specific scripts like schema dash H two dot sql or Schema dash postrescl dot sql. You can control which platform it uses with Spring dot sql dot in it dot platform.

Speaker 1

Very convenient for quick starts. Okay, moving up a level to Spring data, that's a big deal. What's the core idea? There.

Speaker 2

Spring Data revolves around repository interfaces think cred repository or paging and sorting repository.

Speaker 1

So I just define an interface.

Speaker 2

You define an interface that extends one of those, and bam, you instantly get standard methods like save fine by I, find old, delete biog implemented for.

Speaker 1

You without writing any SQL often.

Speaker 2

Yes, it uses query derivation based on method names. If you name a method find by email string email, spring data figures out the query. It's pretty magical.

Speaker 1

That is a huge time saver. Okay, so what about the specific implementations like Spring data JDBC.

Speaker 2

Spring Data JDBC gives you enhanced support on top of plane JDBC. It's built around the aggregate root concept from Domain driven Design Aggregate root. Yeah, it helps you model your data relationships cleanly, ensuring consistency, especially when you have complex optic graphs. It uses things like aggregate reference to manage links between entities.

Speaker 1

Okay, and the really popular one, Spring and Data JPA.

Speaker 2

Right. JPA simplifies using the jag of Persistence API, boot, auto Computers, a data source platform, Transaction Manager, NAT Manager, factory all the JPA infrastructure.

Speaker 1

And I just use annotations on my classes exactly at entity to market class at ID for the primary key, at generated value for generated IDs, at many, tone, at many tominy for relationships. And it can create the tables too, Right, I don't need schema dot A scale anymore often.

Speaker 2

Yes, JPA providers like Hibernate can generate the DDL Data Definition Language to create or update your schema based on your entity definitions when the app starts. Another big simplification.

Speaker 1

Wow. Okay, so that's data access covered. But what if I want to expose this data as a rest API without writing any controllers myself? Is that possible?

Speaker 2

It absolutely is. That's where Spring Data rest comes in. It's amazing.

Speaker 1

What does it do.

Speaker 2

It automatically builds a hyper media driven rest API directly from your Spring Data repository interfaces. Just add the dependency seriously, just like that, pretty much. Add the Spring Data restel explorer starter and you instantly get a discoverable API explore at http dot localhost dot a zero ad R. You can browse your resources, see the endpoints. It's incredible for rapid API prototyping.

Speaker 1

An API explorer pops up automatically. That's fantastic.

Speaker 2

Yeah, and you can customize the endpoint paths, the names used for resources, and so on using the at repository rest resource annotation if the defaults aren't perfect.

Speaker 1

Okay, that's seriously powerful. Now, what about new SQL databases like Mango dB or reddis is integration just as smooth.

Speaker 2

Pretty much. Yeah. For Mango dB adds Spring Bootstarter data. Mangun boot auto configures the connection you typically interact using Mango template or Mongo.

Speaker 1

Operations anything specific to now like with Docker.

Speaker 2

Yeah, if you're using doctor composed, make sure to set the Mango endb database environment variable so it knows which database to initialize. Oh, in Spring data, Mango dB adds a class field to your documents to help with mapping back to Java objects.

Speaker 1

Okay, and reddis for cashing or key value stuff.

Speaker 2

Similar story, add Spring Bootstarter data reddis. You can map your Java objects to Rettis hashes using the at rettis hash annotation. It stores data with clear keys like retroboard for the type and retroboard dot ued for specific instances.

Speaker 1

So SQL or nosea boot really smooths out the setup and basic operations. Okay, let's switch paradigms completely reactive programming. The book mentions the Reactive Manifesto. What's the core idea there?

Speaker 2

The Reactive Manifesto back from twenty fourteen lays out the traits of reactive systems. They need to be responsive, resilient, elastic and message driven.

Speaker 1

So quick, fault tolerant, scalable and using async messages exactly.

Speaker 2

It's about building systems that handle load and failure gracefully. Using asynchronous communication and back pressure is key so components don't get overwhelmed. It's a different way of thinking compared to traditional blocking code.

Speaker 1

A big shift. And how does Spring implement this on the JVM?

Speaker 2

Primarily through Project Reactor. It's a library based on the reactive stream specification that's a standard for ACYNC stream processing with back pressure. Reactor brings this non blocking, event driven approach to Java.

Speaker 1

And what are the main building blocks developers use in reactor?

Speaker 2

The two core types are monot and flux.

Speaker 1

T Mono andflux okay.

Speaker 2

Mono represents the stream of zero or one item. Think of it like an ACNC optional. Flux represents the stream of zero to n items. It's an asynchronous sequence.

Speaker 1

Got it? And when you use this with springboot, how do you reactive web and data look different.

Speaker 2

For reactive web you add spring boots Starter web flux boot, autoconfigures it, and crucially it defaults to using Netty instead of Tomcat as the server.

Speaker 1

Because netti is non blocking.

Speaker 2

Exactly ensures the whole iostack is non blocking. For reactive data access, you'd use reactive repository interfaces like reactive CRUD repository, so.

Speaker 1

The entire request path from web to database and back can be non blocking.

Speaker 2

That's the goal. It's essential for applications needing really high concurrency and low latency.

Speaker 1

Okay, a powerful option for specific needs. Now let's talk about communication within and between applications using messaging. How does spring boot handle events?

Speaker 2

Well, Spring itself has core events like context refreshed event. Spring boot adds its own like application ready event. We mentioned that one earlier fires when the app is fully ready.

Speaker 1

Can I create my own events for internal communication like decoupling parts of my app?

Speaker 2

Oh? Absolutely, it's a great pattern. You can create custom event classes by extending application event or even simpler, just anne tape method with at event listener.

Speaker 1

So I could have say a user activated event.

Speaker 2

Exactly publish that event when a user becomes active. Then have another component listen for at event listener and if you want the listener to run without blocking the publisher, just add at at ASNC. Really powerful for loose coupling.

Speaker 1

Nice. What about more traditional messaging systems JMS.

Speaker 2

Easy integration, add the starter for active MQ Spring Bootstarter, Active MQ or Artemis Spring bootstarter.

Speaker 1

Artemis and sending and receiving.

Speaker 2

You use JMS template dot convert and send to publish messages. To listen, you just annotate a method with at JMS listener specifying the Q or topic.

Speaker 1

Name and pubsub versus point to point.

Speaker 2

Simple property dot spring dot JMS dot pubsubdomain true switches it to topic mode published subscribe.

Speaker 1

Okay, straightforward. What about AMQP and RabbitMQ that has more complex concepts right exchanges, bindings it.

Speaker 2

Does MQP uses exchanges, bindings and queues. Messages go to an exchange first. Bindings are rules that wrote messages from an exchange to specific queues. Queues are where consumers pick messages up.

Speaker 1

So the exchanges like the central post office, bindings are the sorting rules. Queues are the mailboxes.

Speaker 2

Perfect analogy, and there are different types of exchanges for different routing logic direct uses a specific routing key, fan out broadcast to all bound cues. Topic uses wildcard routing keys like user or audit hashtag headers roots based on message headers.

Speaker 1

Lots of flexibility there. How to spring AMQP help.

Speaker 2

It gives you annotations like at rabbit listener to easily consume messages, and you can programmatically declare queues, exchanges and bindings using at qu at exchange and at que binding annotations, which simplifies set up a lot.

Speaker 1

Okay, powerful routing options. What about real time two way communication like for chat apps or live dashboards?

Speaker 2

For that, you typically use web sockets. It's a protocol providing full duplex communication over a single TCP connection. Client and server can both send messages anytime, and.

Speaker 1

People often use STOMP over web sockets.

Speaker 2

Yes. STOMP simple text oriented messaging protocol adds a layer on top providing message headers, destinations, and a pub submodel, making it easier to route messages to specific users or topics within the web socket connection.

Speaker 1

How do you set that up? In boot?

Speaker 2

Add Spring Bootstarter web socket UH on the server you use at enable web socket message broker and configure endpoints and brokers using web socket message broker configure.

Speaker 1

And the book also mentions our socket what's that for?

Speaker 2

Our socket is a newer binary protocol designed for high performance, low latency communication, especially between micro services.

Speaker 1

Binary not tech space.

Speaker 2

Right, and it supports more interaction models than just request response. You have fire and forget request stream, server streams, data back and channel fully bi directional streams.

Speaker 1

How do you use it with springboot ad.

Speaker 2

Spring bootstarter socket? You use our socket request or on the client side and at message mapping on the server side to handle incoming requests or streams. It's geared towards high throughput scenarios.

Speaker 1

Okay, so boot really covers the whole spectrum of communication needs. Now let's talk about getting these apps production ready spring Boot. Actuator is key here right for observability.

Speaker 2

Absolutely, Actuator is your go to for production insights. Yeah. It exposes a ton of useful information and management endpoints over HTTP or JMX, think metrics, health checks, environment variables, thread dumps, logger levels.

Speaker 1

Like a built in dashboard for your apps internals kind of.

Speaker 2

Yeah. It gives monitoring tools the hooks they need.

Speaker 1

What are the most critical endpoints?

Speaker 2

The main prefix is actuator. The most important one enabled by default is actuator Health. It gives a basic updown status but can be customized to check dependencies too and others. Actuator info for app info, Actuator Metrics for detailed metrics, Actuator loggers to view and change log levels on the fly, Actuator beans to see all the Spring beans, Actuator events for environment properties, Actuator audit events for security stuff. Lots of useful ones?

Speaker 1

Are they all enabled by default? Seems like some could be?

Speaker 2

Some good point? No, Only health and sometimes info are exposed over HTTP by default. You need to explicitly enable others using the management Dot endpoints dot web dot exposure DOT.

Speaker 3

Include property like health infometrics exactly, and for sensited ones like loggers or envy, you absolutely must secure them, usually by integrating Actuator with Spring security and requiring a specific role like actuator admin makes sense.

Speaker 1

Can I create my own Actuator endpoints for application specific stuff?

Speaker 2

Yep, It's surprisingly easy. You create a class annotated with that endpoint, and then methods inside annotated with that readoperation for deed, at write operation for PSD or at delete operation lets you expose custom state or operations.

Speaker 1

What about custom health checks, like checking if a downstream service is reachable?

Speaker 2

Definitely you implement the health Indicator interface. This lets you plug in custom logic, check a database, call an external API, verify a business rule, and have its status contribute to the overall Actuator health endpoint a much riger picture of health.

Speaker 1

Okay, and for the full observability trifecta metrics, logs tracing. How does actuator fit in?

Speaker 2

Actuator is the main integration point, especially for metrics. It uses micrometer underneath micrometer. Yeah, it's a vendor neutral application metrics facade think SLF four J. But for metrics, Actuator exposes micrometer metrics.

Speaker 1

Can I add my own business metrics easily?

Speaker 2

Yes? You can inject the meter registry and create counters, timers, gauges directly, or even better, use the ad observed annotation from Micrometer Observation AOP for a more declarative approach. You can also use things like handler interceptor to automatically time web requests.

Speaker 1

Okay, So metrics are covered. What about logs and distributed tracing?

Speaker 2

For logs, you typically can figure something like log back using logbackspring dot xml to output structured logs like JSON and then ship them off to a log aggregation system like Grafonoloki or elastic search.

Speaker 1

And tracing across micro services.

Speaker 2

For that you integrate with distributed tracing systems. Spring Boot has great support for Jaeger and Zipkin, often visualized with Graffana Tempo. My Chrometer Tracing handles the instrumentation.

Speaker 1

And Graffana brings it all together exactly.

Speaker 2

Use Prometheus often to scrape the actuated Prometheus metrics endpoint looking for logs, Tempo for traces, and then Graffana provides the unified dashboards to visualize everything. That's your full observability stack.

Speaker 1

That's a comprehensive setup. Okay, ensuring quality before production testing. How does springboot help there?

Speaker 2

It builds on the standard spring test framework but adds autoconfiguration goodness. The main tool for integration testing is at springboot.

Speaker 1

Test and that loads the whole application context.

Speaker 2

Yes, it loads the full context, making it very realistic. You can control the web environment, random port, moc numbi, past properties ARGs. It's flexible but can be slower.

Speaker 1

Right, loading everything can be slow. What if I just want to test one layer like my web controllers.

Speaker 2

That's where test likeses are brilliant. They load only the parts of the context relevant to a specific layer, making tests much faster. Example, at webmvictest is a big one. It focuses just on the web layer, your controllers, filters, et cetera. It auto configures mock them VC for sending mock HTTP requests and often uses at mockbeing to mock out service dependencies.

Speaker 1

So you test the controller in isolation pretty much.

Speaker 2

There's also at json test for testing Jason serial de serialization logic.

Speaker 1

Specifically, and for the data layer testing repositories.

Speaker 2

You have slices like at data JPay tests for jpa at data, Mango tests for manga deb at data edis test at jdbt tests. These load just a data configuration and often use an embedded database or mock the noseql client.

Speaker 1

But embedded databases aren't always the same as production. How do you test against a real database like postgress bowl reliably?

Speaker 2

That's the perfect use case for test containers. It's fantastic that does it work. You annotate your test class to use a container like a container for a post riscal container test container starts a real postgressfol instance in Docker just for your test run.

Speaker 1

Wow, a real database instance.

Speaker 2

For tests yep, and with at service connection, spring Boot tests can automatically configure your application context to connect to that container. It makes integration tests incredibly reliable. The at restart scope annotation is also useful to keep the container running between test methods in the same class, speeding things up.

Speaker 1

That's amazing for confidence, okay, equally critical security. How does spring boot security work under the hood.

Speaker 2

It's built around a chain of servelet filters. The entry point is usually delegating filter proxy, which passes the request to a filterchain proxy. This proxy manages multiple security filter chain instances, each potentially handling different URL patterns or security concerns. It processes the HTTP servelet request and HTTP servelet response.

Speaker 1

How do I add it to my project?

Speaker 2

Just add the spring boot starter security dependency. Springboot autoconfigures basic security immediately, which means usually it enables HTTP basic informed log in, secures all end points by default, and generates a default user with a random password into the console and startup just enough to get you started securely.

Speaker 1

How do I manage users properly, not just the default and memory one.

Speaker 2

For simple cases, you can configure in memory user details manager, but for real apps you implement the user detail service.

Speaker 1

Interface and that talks to my database.

Speaker 2

Typically, yes, you'd inject your user repository into your custom user detail service implementation to load user details. Spring security then uses a DEO authentication provider to check passwords against what your service.

Speaker 1

Returns, and you configure log in methods like form log in.

Speaker 2

Yeah. Using the HTDP security Configuration object, you call methods like HTTP basic or form log in to enable those mechanisms. You also configure authorization rules there, like request matchers, admin dot has role adm an.

Speaker 1

What about cores? That's always tricky.

Speaker 2

With front ends trucial, you can figure cores using a course configuration source being usually within your security configuration to allow requests from your front ends.

Speaker 1

Origin and reactive security.

Speaker 2

For web flex it's similar conceptually, but uses re active types. You can figure server HTTP security instead of HTTP security, and things like login handlers use reactive interfaces like server authentication success handler.

Speaker 1

Can I test security rules easily without doing a full log in and every test?

Speaker 2

Yes. The atwith mock user annotation is perfect for this. You can apply it to your at webmvictest or at webflux. Test methods to simulate a request coming from an already authenticated user with specific roles saves a ton of setup.

Speaker 1

Very handy. What about social login OOF two with GitHub.

Speaker 2

Or Google also well supported? Add Spring Bootstarter O two client. You can figure your client ID in secret from the provider, use environment variables or secrets management, never hardcode them. Spring Security handles the whole redirect dance and authentication flow smooth.

Speaker 1

The book also mentions Spring Authorization Server. What's that? Why would I run my own authorization server?

Speaker 2

That's for when you want to be the identity provider, maybe for your own suite of micro services or partner applications. Spring Authorization Server is a dedicated project providing a compliant OOF two point one and open id Connect one point zero server implementation built on Spring Security. You can figure clients scopes like users, dot red, token, settings, etc. Gives you full control over the identity aspect.

Speaker 1

Okay, so full spectrum of security. Let's shift to performance and deployment Spring boot native and AOT with galvim. What's the big deal with GraalVM.

Speaker 2

Galvm is a high performance JDK distribution key features are faster JIT compilation, support for multiple languages, and most importantly for this discussion, its native image capability.

Speaker 1

Native image What does that actually mean for my app?

Speaker 2

It means compiling your Java Cottlin code ahead of time AOT into a standalone native executable for a specific platform like Linux by sixty four. This executable does not require a JVM to run.

Speaker 1

No JVM. What's the benefit?

Speaker 2

Huge benefits. Drastically faster startup times think milliseconds instead of seconds, and significantly lower memory footprint, maybe tens of megabytes instead of hundreds. It's the game changer for serverless functions, containers anywhere resources or startup speed matter.

Speaker 1

That is a massive difference. How do you build one with Springboot?

Speaker 2

Typically using the build tool plugins like Doug gritlue Boot build Image or the Maven equivalent. This often uses cloud native build packs behind the scenes to perform the native compilation inside a container and package the result.

Speaker 1

And what spring boots specific role the AOT part exactly.

Speaker 2

The standard Java reflection and dynamic proxies that spring uses heavily are difficult for grailvm's static analysis, so spring boots AOT engine runs at build time, analyzes your application context figures out what beams, proxies and configurations will be needed at runtime, and generates extra source code and hints.

Speaker 1

So it pre computes the runtime configuration essentially.

Speaker 2

Yes, it generates code that GRAILVM can analyze statically, allowing the native compilation to succeed while preserving Springs functionality.

Speaker 1

What if my code does something really dynamic, like reflection that the AOT engine misses.

Speaker 2

That's where you need runtime hints. Can implement a runtime hints registrar interface to programmatically tell the AOT engine about specific reflection needs, resource loading, serialization, or proxy requirements that it couldn't detect automatically.

Speaker 1

Okay, so native images offer huge performance games enabled by Springs AOT processing. Now looming out to architecture spring Cloud for microservices. How to boot and cloud fit together.

Speaker 2

They're designed to work hand in glove. Springboot is perfect for building the individual microservices self contained runnable jrs with embedded servers. It aligns perfectly with those twelve factor app principles needed for micro services.

Speaker 1

Like codebase canfig dependencies processes exactly.

Speaker 2

Springboot gives you the ideal building block. Spring Cloud then provides the tools to handle the interactions and patterns needed in a distributed microservice system.

Speaker 1

And when we talk cloud development, it's more than just deploying to AWS right.

Speaker 2

It's about building applications natively for the cloud environment, leveraging elasticity, fault tolerance, managed services, moving beyond just lifting and shifting old apps to designing for the cloud from the start.

Speaker 1

So what are some key spring Cloud technologies that help manage this complexity?

Speaker 2

Okay, several key ones. First, spring Cloud Console or Eureka or Kubernety. Service discovery. It handles service registration and discovery. Services register themselves and clients can dynamically find where other services are running without hardcoding URLs. It can also manage externalized configuration.

Speaker 1

Essentral for dynamic environments.

Speaker 2

What else spring Cloud open fame. This makes calling other rest services incredibly easy. You just define a Java interface with annotations and fine handles creating the HTTP client, doing service discovery, client side load balancing. It feels like calling a local method.

Speaker 1

Nice abstraction. What about secrets, databased passwords, apikes?

Speaker 2

Spring Cloud Vault. It integrates with how she co op Vault or other secret managers to securely inject secrets into your application and run time. No more secrets and properties, files or environment variables. Volt handle secure storage, access control and even secret.

Speaker 1

Rotation critical for security. What about the entry point to the whole system.

Speaker 2

That's spring Cloud Gateway. It's an API gateway built on spring webslucks, so it's reactive and non blocking. It provides a single point of entry for all external requests. It can handle routing, applying security filters like rate limiting or authentication, load balancing, path rewriting, and implementing resilience patterns like circuit breaking.

Speaker 1

Circuit breaks.

Speaker 2

Yeah, if a downstream service starts failing, the gateway can trip the circuit and stop setting request to it for a while, preventing cascading failures and returning a fallback response instead.

Speaker 1

Smart and finally, orchestrating all these containerized services Kubernetes absolutely.

Speaker 2

Kubernetes k eights is the standard for container orchestration spring Cloud. Kubernetes provides integrations spring Cloud Starter, Kuberneteses Client all so your boot apps can seamlessly leverage K eight's features like config maps for configuration, secrets for secrets management, and KAID service discovery, all without much code change you deploy using Kid's deployment and service ammal manifests.

Speaker 1

So spring cloud provides the connective tissue for boot micro services in a cloud environment. Okay, one more advanced topic, extending boot itself with custom starters. Why bother creating your own?

Speaker 2

The main reasons are speed, consistency, and maintainability within your organization or team. If you have a common cross cutting concern like specific auditing, security checks or client library setup, you can package it as a starter.

Speaker 1

So new projects just include your starter exactly.

Speaker 2

They get all that boilerplate and configuration handled automatically, ensuring everyone follows the same pattern. It reduces setup time, It makes codebases more consistent and easier to maintain.

Speaker 1

Is it like using spring zone at enable annotations at enable web NBC at enable caching?

Speaker 2

Very similar concept. Those annotations trigger auto configuration. You can create your own custom that enable my feature annotation as part of your starter to make it easy for users to opt in to your functionality.

Speaker 1

Declaratively, how are starters typically structured?

Speaker 2

Usually as two modules. An autoconfigure module contains the core logic, the at configuration or at autoconfiguration classes often conditional using at conditional non annotations, any configuration properties, classes and the logic itself like aspects or beans.

Speaker 1

And the second module.

Speaker 2

A starter module. This one's usually very simple. It just declares dependencies on the autoconfigure module and any other third party libraries. Your feature needs users, then just depend on your my feature spring boots starter.

Speaker 1

Can you give a quick example.

Speaker 2

The book uses a my retroadit Starter example. It is a custom in my retrodit annotation an aspect my retro audit aspect uses at a round advice to intercept calls to annotated methods and log ondit info, and the auto configuration a my retroaddic configuration class marks at autoconfiguration conditionally enables the aspect maybe based on a property or if the custom at enable my retroad annotation is present, then you register this autoconfiguration clas in the special meta and

f spring org dot, spring framework, dot boot, dot autoconfigure, dot autoconfiguration dot imports.

Speaker 1

File so it automatically wires up the auditing aspect if the starter is included and enabled. Clever okay. Wrapping up the book touches on some newer projects. What's exciting on the horizon.

Speaker 2

First, Spring modulith. This is interesting. It's not micro services, but it helps structure larger spring Boot modulates into well defined modules within the same.

Speaker 1

Codebase, modularity inside the monolith exactly.

Speaker 2

It helps enforce boundaries between modules, verifies dependencies of build time, and can even generate diagrams of your module structure. It encourages looser coupling, often through event driven communication between modules instead of direct calls. It's about making monoliths more manageable, a pragmatic approach. What else, Spring ai this is huge. It's a new framework bringing AI capabilities, especially large language models lms like GBT four directly into Spring applications.

Speaker 1

Like Python's lang chain but for Java Spring.

Speaker 2

Kind of yeah. It simplifies interacting with AIME models using concepts like chat client prompt templates and handling embeddings numerical representations of text for semantic understanding. Makes building AI powered features in Spring much.

Speaker 1

Easier, very cool and performance improvement.

Speaker 2

Virtual threads from Jaba twenty one are now supported in Spring Boot three point two plus okios. You just flip a switch Spring dot threads dot virtual dot enable true and tomcatter jety can start using lightweight virtual threads for handling requests.

Speaker 1

What's the benefit.

Speaker 2

Potentially massive throughput improvements for iobound applications without complex ACYN code because you can have millions of virtual threads with very little overhead compared to traditional platform threads.

Speaker 1

Wow, simple switch, big impact potentially. And finally, Graphql.

Speaker 2

Yeah, graph L is gaining traction as an alternative to rest It lets clients request exactly the data they need, no more, no less, reducing overfetching. Spring for Graphql provides excellent integration.

Speaker 1

How does it work?

Speaker 2

You define your API schema using GRAPHQOLS, Schema Definition Language SDL and a dog graphcuels file. Then in your Spring code you use annotations like at query mapping and at mutation mapping on methods to implement the resolvers for your schema fields. It also integrates with tools like graphuel for interactive testing.

Speaker 1

So a different way to build APIs fully supported. Wow. Okay, we have covered a lot of ground here. It's been a real deep dive, hasn't it.

Speaker 2

Absolutely from the core ideas of autoconfiguration, right.

Speaker 1

Through building web apps, data access messaging, then production stuff like actuator testing, security.

Speaker 2

Dative images. Spring Cloud for micro services even custom starters and bleeding edge things like AI and virtual threads.

Speaker 1

It really paints a picture of a comprehensive ecosystem.

Speaker 2

It does. It's about enabling developers to build sophisticated systems faster and more reliably, handling the boiler plate so you can focus on the unique value.

Speaker 1

So for you listening, what really stands out is how Spring boot, with this whole rich ecosystem, acts like this incredible orchestrator right. It lets you the developer, build complex applications quickly without getting totally bogged down on the plumbing. It empowers you to focus on your business logic. You can really see how all these pieces from a simple at rest controller to a full Kate's deployment fit together.

Speaker 2

It gives you the tools and the patterns to build modern software effectively.

Speaker 1

And as we saw with things like Spring Modulus and Spring AI, this whole landscape just keeps evolving, doesn't it. So here's the thought to leave you with, what if the next big leap isn't just about how services talk to each other, but how entire applications, maybe modular ones powered by AI can adapt and reconfigure themselves on the fly,

almost like biological systems. What new Aha moments are waiting just around the corner in software architecture, Something to chew on as you continue your own explorations in this fascinating world.

Transcript source: Provided by creator in RSS feed: download file
For the best experience, listen in Metacast app for iOS or Android